regex: replace '@@' with '@' and '@' with some string

Viewed 87

Problem: I'm new to regex, I have string
"this @ is @@ sample @@@ string @@@@" and have target string "xxx"
so process is,
replace '@' to "xxx" (target string)
replace '@@' to '@'

so output will look like this,
this xxx is @ sample @xxx string @@


* what I tried (scala),

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

But problem is what if source string contains \u0000, it will aslo replace with @

so, comes to regex Is there possible to select @ which are not subsequent twice, so in case of "this @ is @@ sample @@@ string @@@@" we will replace the target string with only that are not subsequent twice, example

"this @ is @@ sample @@@ string @@@@" (matched two result will replace with target string xxx)
and than simply .replaceAll("@@", "@")

2 Answers

You can use

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

See a Scala demo, output:

this xxx is @ sample @xxx string @@

The @@? pattern matches either one or two @ chars. If the match value is of length 1, the replacement is xxx, else, it is @.

No regex required. (At least no overt regex usage.)

"this @ is @@ sample @@@ string @@@@"
  .split("@@", -1)
  .map(_.replaceAll("@", "xxx"))
  .mkString("@")
//res0: String = this xxx is @ sample @xxx string @@
Related