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

前端 未结 1 354
情深已故
情深已故 2020-12-11 19:19

I\'m trying to do something like this:

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


        
相关标签:
1条回答
  • 2020-12-11 20:15

    It seems that you are looking for 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("someregex");
    Matcher m = p.matcher(s);
    
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, methodFoo(m.group()));
    }
    m.appendTail(sb);
    
    String result = sb.toString();
    
    0 讨论(0)
提交回复
热议问题