Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

jdavidb (1361)

jdavidb
  (email not shown publicly)
http://voiceofjohn.blogspot.com/

J. David Blackstone has a Bachelor of Science in Computer Science and Engineering and nine years of experience at a wireless telecommunications company, where he learned Perl and never looked back. J. David has an advantage in that he works really hard, he has a passion for writing good software, and he knows many of the world's best Perl programmers.

Journal of jdavidb (1361)

Monday February 23, 2009
08:45 AM

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

[ #38537 ]

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();
}

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • 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);
       }

    • Or even much better: [sun.com]

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

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

      --
      J. David works really hard, has a passion for writing good software, and knows many of the world's best Perl programmers