Java tip of the day: regex s///g (global replacement)

jdavidb on 2009-02-23T13:45:39

It's hideous, but I think it does the trick:

public static String subst(String string, String regex, String repl) {
  Pattern pat = Pattern.compile(regex);
  Matcher m = pat.matcher(string);
  StringBuilder sb = new StringBuilder();
  int prevend = 0;
  while (m.find()) {
    int start = m.start(0);
    int end = m.end(0);
    String val = m.group(0);
    sb.append(string.substring(prevend, start));
    sb.append(repl);  // sb.append(transform(val));
    prevend = end; 
  }
  sb.append(string.substring(prevend));
  return sb.toString();
}


Even easier

ChrisDolan on 2009-02-24T05:26:36

That's way too complicated. This is easier:

   public static String subst(String string, String regex, String repl) {
      Pattern pat = Pattern.compile(regex);
      Matcher m = pat.matcher(string);
      return m.replaceAll(repl);
   }

or even

   public static String subst(String string, String regex, String repl) {
      return Pattern.compile(regex).matcher(string).replaceAll(repl);
   }

Re:Even easier

ChrisDolan on 2009-02-24T05:28:45

Or even much better:

   public static String subst(String string, String regex, String repl) {
      return string.replaceAll(regex, repl);
   }

Re:Even easier

jdavidb on 2009-02-24T15:07:06

Doesn't work if you need the variant in the comments, where you transform the matched expression to generate the replacement.