elm*_*elm 1 string scala scala-collections
在字符串中,如何替换以给定模式开头的单词?
例如更换每一个开头的字"th",用"123",
val in = "this is the example, that we think of"
val out = "123 is 123 example, 123 we 123 of"
Run Code Online (Sandbox Code Playgroud)
即如何在保留句子结构的同时替换整个单词(例如考虑逗号).这不行,我们想念逗号,
in.split("\\W+").map(w => if (w.startsWith("th")) "123" else w).mkString(" ")
res: String = 123 is 123 example 123 we 123 of
Run Code Online (Sandbox Code Playgroud)
除了标点符号之外,文本还可以包括多个连续的空格.
您可以使用该\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
Run Code Online (Sandbox Code Playgroud)