Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

regex - scala exactly matching a word in a given string

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...