Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String Scala字符串替换符合模式的整个单词_String_Scala_Scala Collections - Fatal编程技术网

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

String Scala字符串替换符合模式的整个单词,string,scala,scala-collections,String,Scala,Scala Collections,在字符串中,如何替换以给定模式开头的单词 例如,将以“th”开头的每个单词替换为“123” 即如何在保留句子结构的同时替换整个单词(例如,考虑逗号)。这行不通,我们漏掉了逗号 in.split("\\W+").map(w => if (w.startsWith("th")) "123" else w).mkString(" ") res: String = 123 is 123 example 123 we 123 of 除了标点符号外,文本还可能包含多个连续空格。如果在行中添加“whi

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

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

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

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
如果在行中添加“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
您可以使用该模式查找以
th
开头,后跟其他单词字符的单词,然后将所有匹配项替换为“123”

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


这就产生了“123is是123e的例子,123at我们123ink的”哦!是的,我忘了读那部分@dcastro您的正则表达式是正确的+1,因为这会产生“123is是123e示例,123at我们123ink的“哦!是的,我忘了读那部分@dcastro您的正则表达式对于that@dcastro如果单词以“th”结尾或包含“th”,则正则表达式可能会失败,因为它需要一个单词boundary@dcastro如果单词以“th”结尾或包含“th”,则正则表达式可能会失败,因为它需要单词边界
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