Reputation: 880
I want to remove the sequesnce "-~-~-" if it repeats in a string, but only if they are together. I have tried to create a regex based on the removing of multiple white spaces regex:
test.replaceAll("\\s+", " ");
Unfortunately I was unsuccessful. Can someone please help me write the correct regex? thanks.
Example:
string test = "hello-~-~--~-~--~-~-"
output:
hello-~-~-
Another example
string test = "-~-~--~-~--~-~-hello-~-~--~-~--~-~-"
output:
-~-~-hello-~-~-
Upvotes: 1
Views: 91
Reputation: 62155
The regex is:
test.replaceAll("(-~-~-){2,}", "-~-~-")
replaceAll
replaces all occurrences matched by the regex (the first parameter) with the second parameter.
the ()
groups the expression -~-~-
together, {2,}
means two or more occurrences.
EDIT
Like @anubhava said, instead of using -~-~-
for the replacement string, you could also use $1
which backreferences the first capturing group (i.e. the expression in the regex surrounded by ()
).
Upvotes: 2