Java Regex String#replaceAll Alternative

后端 未结 2 1141
时光说笑
时光说笑 2020-12-07 03:18

I\'ve been trying to devise a method of replacing multiple String#replaceAll calls with a Pattern/Matcher instance in the hopes that it would be faster than my current metho

2条回答
  •  囚心锁ツ
    2020-12-07 03:41

    This is a relatively straightforward case for appendReplacement:

    // Prepare map of replacements
    Map replacement = new HashMap<>();
    replacement.put("bla", "hello,");
    replacement.put("red", "world!");
    // Use a pattern that matches three non-@s between two @s
    Pattern p = Pattern.compile("@([^@]{3})@");
    Matcher m = p.matcher("@bla@This is a @red@line @bla@of text");
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        // Group 1 captures what's between the @s
        String tag = m.group(1);
        String repString = replacement.get(tag);
        if (repString == null) {
            System.err.println("Tag @"+tag+"@ is unexpected.");
            continue;
        }
        // Replacement could have special characters, e.g. '\'
        // Matcher.quoteReplacement() will deal with them correctly:
        m.appendReplacement(sb, Matcher.quoteReplacement(repString));
    }
    m.appendTail(sb);
    String result = sb.toString();
    

    Demo.

提交回复
热议问题