scala exactly matching a word in a given string

前端 未结 1 1378
一生所求
一生所求 2020-12-21 14: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\         


        
相关标签:
1条回答
  • 2020-12-21 15:13

    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.

    0 讨论(0)
提交回复
热议问题