0

I'm trying to strip a string of all sequences that begin with a string "GUGU" and and end with something like "AGAG". The closest I've gotten is

replaceAll("GUGU(.*)AGAG", "")

but all that does is replace the "largest" instance. Meaning if there are multiple occurrences of GUGU*AGAG in a string, it only matches the outermost. So what could I do to get this to work for every instance of the regex in the string?

1 Answers1

0

Use a reluctant rather than a greedy quantifier (see the documentation):

String s = "hello GUGU hello AGAG hello GUGU hello AGAG";

// greedy
System.out.println(s.replaceAll("GUGU(.*)AGAG", ""));
// prints "hello "

// reluctant
System.out.println(s.replaceAll("GUGU(.*?)AGAG", ""));
// prints "hello  hello "
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255