2

我正在尝试使用 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

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"

我怎样才能做到这一点?

4

1 回答 1

4

这取决于您要如何定义“单词”。如果“单词”是您通过空格字符序列拆分字符串时得到的,那么您可以编写:

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

where(?<=^|\\s)表示“在字符串开头或空格之前”,并(?=\\s|$)表示“后跟空格或字符串结尾”。

请注意,这会将(例如)字符串 Tell my wife hello.视为包含四个“单词”,其中第四个是hello.而不是 hello。您可以通过以更复杂的方式定义“单词”来解决这个问题,但您需要先定义它。

于 2012-11-30T20:30:47.330 回答