用数据替换文本&匹配组内容

时间:2014-10-22 03:36:28

标签: java regex

我不相信我在搜索时看到了这一点(相信我,我花了很多时间寻找这个)以获得解决方案,所以这里就是这样。

目标: 匹配字符串中的正则表达式并将其替换为包含匹配值的内容。

目前正在使用的正则表达式:

\b(Connor|charries96|Foo|Bar)\b

为了记录,我在正则表达式中吮吸这不是最好的方法。

我当前的代码(以及我尝试过的其他几种方法)只能在遇到多个匹配时遇到的第一个匹配项中替换文本。

private Pattern regexFromList(List<String> input) {
    if(input.size() < 1) {
        return "";
    }

    StringBuilder builder = new StringBuilder();
    builder.append("\\b");
    builder.append("(");
    for(String s : input) {
        builder.append(s);
        if(!s.equals(input.get(input.size() - 1)))
        {
            builder.append("|");
        }
    }
    builder.append(")");
    builder.append("\\b");

    return Pattern.compile(builder.toString(), Pattern.CASE_INSENSITIVE);
}

示例输入:

charries96's name is Connor.

使用TEST作为数据来预先匹配

的示例结果
TESTcharries96's name is TESTcharries96.

使用示例输入所需的结果:

TESTcharries96's name is TESTConnor.

以下是我目前替换文字的代码:

if(highlight) {
    StringBuilder builder = new StringBuilder();
    Matcher match = pattern.matcher(event.getMessage());
    String string = event.getMessage();

    if (match.find()) {
        string = match.replaceAll("TEST" + match.group());
        // I do realise I'm using #replaceAll but that's mainly given it gives me the same result as other methods so why not just cut to the chase.
    }
    builder.append(string);
    return builder.toString();
 }

修改RegExr

上获得所需结果的工作示例

1 个答案:

答案 0 :(得分:0)

这里有一些问题:

  • 您正在按原样获取用户输入并构建正则表达式:

    builder.append(s);
    

    如果用户输入中有特殊字符,则可能会将其识别为元字符并导致意外行为。

    如果要在传入字符串时匹配字符串,请始终使用Pattern.quote

    builder.append(Pattern.quote(s));
    
  • Matcher.replaceAll是一个高级功能,重置匹配器(重新开始匹配),并搜索所有匹配项并执行替换。在您的情况下,它可以简单:

    String result = match.replaceAll("TEST$1");
    

    StringBuilder应与if语句一起丢弃。

  • Matcher.findMatcher.group是较低级别的功能,用于对您要对匹配进行的操作进行细粒度控制。

    执行替换时,您需要使用Matcher.appendReplacementMatcher.appendTail构建结果。

    Matcher.find一起使用while循环(而不是if语句)来搜索并执行所有匹配的替换。