正则表达式:将“@@”替换为“@”,并将“@”替换为某个字符串。

5

问题:

我对正则表达式不熟悉,我有一个字符串:

"this @ is @@ sample @@@ string @@@@"

还有一个目标字符串:

"xxx"

所以处理的过程是:

  • '@'替换为目标字符串"xxx"
  • '@@'替换为'@'

输出结果如下:

this xxx is @ sample @xxx string @@


* 我的尝试(scala),

"this @ is @@ sample @@@ string @@@@".replaceAll("@@", "\u0000").replaceAll("@", "xxx").replaceAll("\u0000", "@")

但问题是,如果源字符串包含 \u0000,它也会被替换为 @

所以,关于正则表达式,有可能选择不相邻两次的 @,因此在 "this @ is @@ sample @@@ string @@@@" 的情况下,我们将仅替换目标字符串中不相邻两次的字符,例如

"this @ is @@ sample @@@ string @@@@"(匹配两个结果将用目标字符串xxx 替换)
然后简单地使用 .replaceAll("@@", "@") 即可


1
尝试使用 https://regexr.com/。这是一个交互式的正则表达式工具,可以进行实验和学习。 - shailesh gupta
1
两种解决方案都完全可行,感谢WiktorStribiżew和@jwvh。 - Pradip Sodha
2个回答

2

您可以使用

val text = "this @ is @@ sample @@@ string @@@@"
val regex = "@@?".r
println(regex.replaceAllIn(text, m => if (m.group(0).length == 1) "xxx" else "@"))

请查看Scala演示,输出:
this xxx is @ sample @xxx string @@

@@?模式匹配一个或两个@字符。如果匹配值长度为1,则替换为xxx,否则替换为@


1
不需要正则表达式。(至少不需要明显使用正则表达式。)
"this @ is @@ sample @@@ string @@@@"
  .split("@@", -1)
  .map(_.replaceAll("@", "xxx"))
  .mkString("@")
//res0: String = this xxx is @ sample @xxx string @@

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接