使用该字符串调用的方法替换模式匹配的每个匹配项

时间:2022-09-13 07:34:58

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!

问题是没有replaceCurrent方法。也许有一个我忽略的等价物。基本上我想用匹配调用的方法的返回值替换每个匹配。任何提示将不胜感激!

1 个解决方案

#1


7  

It seems that you are looking for Matcher#appendReplacement and Matcher#appendTail.

看来你正在寻找Matcher#appendReplacement和Matcher#appendTail。

appendReplacement will do two things:

appendReplacement将做两件事:

  1. it will add to selected buffer text placed between current match and previous match (or start of string for first match),
  2. 它将添加到当前匹配和上一个匹配之间放置的选定缓冲区文本(或第一个匹配的字符串开头),

  3. after that, it will also add replacement for current match (which can be based on it).
  4. 之后,它还会为当前匹配添加替换(可以基于它)。

appendTail will add to buffer text placed after current match.

appendTail将添加到当前匹配后放置的缓冲区文本。

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

#1


7  

It seems that you are looking for Matcher#appendReplacement and Matcher#appendTail.

看来你正在寻找Matcher#appendReplacement和Matcher#appendTail。

appendReplacement will do two things:

appendReplacement将做两件事:

  1. it will add to selected buffer text placed between current match and previous match (or start of string for first match),
  2. 它将添加到当前匹配和上一个匹配之间放置的选定缓冲区文本(或第一个匹配的字符串开头),

  3. after that, it will also add replacement for current match (which can be based on it).
  4. 之后,它还会为当前匹配添加替换(可以基于它)。

appendTail will add to buffer text placed after current match.

appendTail将添加到当前匹配后放置的缓冲区文本。

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