kev670
kev670

Reputation: 880

Remove repeating set of characters in a string

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

Answers (3)

helpermethod
helpermethod

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

Harry
Harry

Reputation: 1472

This is the regex you need:

(-~-~-){2}

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191729

test.replaceAll("(-~-~-)+", "-~-~-");

Upvotes: 1

Related Questions