Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I would like to do some simple String replace with a regular expression in Java, but the replace value is not static and I would like it to be dynamic like it happens on JavaScript.

I know I can make:

"some string".replaceAll("some regex", "new value");

But i would like something like:

"some string".replaceAll("some regex", new SomeThinkIDontKnow() {
    public String handle(String group) {
        return "my super dynamic string group " + group;
    }
});

Maybe there is a Java way to do this but i am not aware of it...

share|improve this question

2 Answers 2

up vote 1 down vote accepted

Here is how such a replacement can be implemented.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExCustomReplacementExample
{
  public static void main(String[] args)
  {
    System.out.println(
      new ReplaceFunction() {
        public String handle(String group)
        {
          return "«"+group.substring(1, group.length()-1)+"»";
        }
      }.replace("A simple *test* string", "\\*.*?\\*"));
  }
}
abstract class ReplaceFunction
{
  public String replace(String source, String regex)
  {
    final Pattern pattern = Pattern.compile(regex);
    final Matcher m = pattern.matcher(source);
    boolean result = m.find();
    if(result) {
        StringBuilder sb = new StringBuilder(source.length());
        int p=0;
        do {
          sb.append(source, p, m.start());
          sb.append(handle(m.group()));
          p=m.end();
        } while (m.find());
        sb.append(source, p, source.length());
        return sb.toString();
    }
    return source;
  }
  public abstract String handle(String group);
}

Might look a bit complicated at the first time but that doesn’t matter as you need it only once. The subclasses implementing the handle method look simpler. An alternative is to pass the Matcher instead of the match String (group 0) to the handle method as it offers access to all groups matched by the pattern (if the pattern created groups).

share|improve this answer

You need to use the Java regex API directly.

Create a Pattern object for your regex (this is reusable), then call the matcher() method to run it against your string.

You can then call find() repeatedly to loop through each match in your string, and assemble a replacement string as you like.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.