【问题标题】:Replace each occurrence matched by pattern with method called on that string用对该字符串调用的方法替换与模式匹配的每个匹配项
【发布时间】:2013-10-28 21:20:53
【问题描述】:

我正在尝试做这样的事情:

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

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

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

【问题讨论】:

    标签: java regex


    【解决方案1】:

    更新:

    从Java 9开始我们可以使用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()`
    

    Java 9 之前

    您可以使用Matcher#appendReplacementMatcher#appendTail

    appendReplacement 会做两件事:

    1. 它将添加到选定的缓冲区文本放置在当前匹配和上一个匹配(或第一个匹配的字符串开始)之间,
    2. 之后,它还会为当前匹配添加替换(可以基于它)。

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

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

    【讨论】:

      猜你喜欢
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      相关资源
      最近更新 更多