In a string, how to replace words that start with a given pattern ?
For instance replace each word that starts with "th"
, with "123"
,
val in = "this is the example, that we think of"
val out = "123 is 123 example, 123 we 123 of"
Namely how to replace entire words while preserving the structure of the sentence (consider for instance the comma). This won't work, we miss the comma,
in.split("\\W+").map(w => if (w.startsWith("th")) "123" else w).mkString(" ")
res: String = 123 is 123 example 123 we 123 of
In addition to punctuation marks, the text may include multiple successive blanks.
You can use the
\bth\w*
pattern to look for words that begin withth
followed by other word characters, and then replace all matches with "123"