Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...