scala 与给定字符串中的单词完全匹配 [英] scala exactly matching a word in a given string

查看:64
本文介绍了scala 与给定字符串中的单词完全匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 scala 替换字符串中单词的完全匹配

I am trying to replace an exact match of a word in a string using scala

"\\bhello\\b".r.replaceAllIn("hello I am helloclass with hello.method","xxx")

output >> xxx I am helloclass with xxx.method

我想要的是替换 helloclass 和 hello.method 中的单词是否恰好是 hello 而不是 hello

what I want is to replace if the word is exactly hello not hello in helloclass and hello.method

xxx I am helloclass with hello.method

如果输入字符串是

"hello.method in helloclass says hello"
"hello.method says hello from helloclass"
"hello.method in helloclass says Hello and hello"

输出应该是

"hello.method in helloclass says xxx"
"hello.method says xxx from helloclass"
"hello.method in helloclass says Hello and xxx"

我该怎么做?

推荐答案

这取决于您想如何定义单词".如果单词"是您按空白字符序列拆分字符串时得到的结果,那么您可以这样写:

This depends on how you want to define "word". If the "words" are what you get when you split a string by sequences of whitespace characters, then you can write:

"(?<=^|\\s)hello(?=\\s|$)".r.replaceAllIn("hello I am helloclass with hello.method","xxx")

其中 (?<=^|\\s) 表示以字符串开头或空格开头"和 (?=\\s|$) 表示后跟空格或字符串结尾".

where (?<=^|\\s) means "preceded by start-of-string or whitespace" and (?=\\s|$) means "followed by whitespace or end-of-string".

请注意,这会查看(例如)字符串 Tell my women hello. 包含四个单词",其中第四个是 hello., 不是 你好.您可以通过以更复杂的方式定义词"来解决这个问题,但您需要先定义它.

Note that this would view (for example) the string Tell my wife hello. as containing four "words", of which the fourth is hello., not hello. You can address that by defining "word" in a more complicated way, but you need to define it first.

这篇关于scala 与给定字符串中的单词完全匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆