scala exactly matching a word in a given string

帅比萌擦擦* 提交于 2019-12-29 09:06:31

问题


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

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

and if the input strings are

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

output should be

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

How can I do that?


回答1:


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")

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

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.



来源:https://stackoverflow.com/questions/13652447/scala-exactly-matching-a-word-in-a-given-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!