符合模式的整个单词的 Scala 字符串替换

Scala string replacement of entire words that comply with a pattern

在字符串中,如何替换以给定模式开头的单词?

例如,将每个以 "th" 开头的单词替换为 "123"

val in = "this is the example, that we think of"
val out = "123 is 123 example, 123 we 123 of"

即如何在保留 句子 的结构的同时替换整个单词(例如考虑逗号)。这行不通,我们错过了逗号,

in.split("\W+").map(w => if (w.startsWith("th")) "123" else w).mkString(" ")
res: String = 123 is 123 example 123 we 123 of

除了标点符号外,文本中还可能包含多个连续的空格。

如果我们在行中添加 "while bathing","replaceALL()" 中的上述正则表达式可能会失败,它需要如下的单词边界。

  val in = "this is the example, that we think of while bathing"
  out = in.replaceAll("\bth\w*", "123")
  out: String = 123 is 123 example, 123 we 123 of while bathing

您可以使用 \bth\w* 模式查找以 th 开头后跟其他单词字符的单词,然后将所有匹配项替换为“123”

scala> "this is the example, that we think of, anne hathaway".replaceAll("\bth\w*", "123")
res0: String = 123 is 123 example, 123 we 123 of, anne hathaway