Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace each occurrence matched by pattern with method called on that string

Tags:

java

regex

I'm trying to do something like this:

public String evaluateString(String s){
    Pattern p = Pattern.compile("someregex");
    Matcher m = p.matcher(s);

    while(m.find()){
        m.replaceCurrent(methodFoo(m.group()));
    }
}

The problem is that there is no replaceCurrent method. Maybe there is an equivalent I overlooked. Basically I want to replace each match with the return value of a method called on that match. Any tips would be much appreciated!

like image 790
Alex Pritchard Avatar asked Oct 28 '13 21:10

Alex Pritchard


People also ask

What do the replaceAll () do?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement .

What is regex in replace?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match in if any of the following conditions is true: The replacement string cannot readily be specified by a regular expression replacement pattern.


1 Answers

Update:

Since Java 9 we can use Matcher#replaceAll​(Function<MatchResult,​String> replacer) like

String result = Pattern.compile("yourRegex")
                       .matcher(yourString)
                       .replaceAll(match -> yourMethod(match.group()));
                                         // ^^^- or generate replacement directly 
                                         // like `match.group().toUpperCase()`

Before Java 9

You may use Matcher#appendReplacement and Matcher#appendTail.

appendReplacement will do two things:

  1. it will add to selected buffer text placed between current match and previous match (or start of string for first match),
  2. after that, it will also add replacement for current match (which can be based on it).

appendTail will add to buffer text placed after current match.

Pattern p = Pattern.compile("yourRegex");
Matcher m = p.matcher(yourString);

StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, yourMethod(m.group()));
}
m.appendTail(sb);

String result = sb.toString();
like image 138
Pshemo Avatar answered Nov 08 '22 18:11

Pshemo