我一直在尝试设计一种用 Pattern/Matcher 实例替换多个 String#replaceAll 调用的方法,希望它比我当前替换字符串中文本的方法更快,但我不知道该怎么做关于它。

这是我要操作的字符串示例:

@bla@This is a @red@line @bla@of text.

如您所见,有多个@ 字符,中间有 3 个字符;情况将永远如此。如果我想替换“@xxx@”的每个实例(其中 xxx 可以是 0 到 9 之间的任何小写字母或数字),那么最有效的方法是什么?目前我正在存储一个 Map,它的键是 '@xxx@' 子字符串,而这些值是我想用的替换该特定子字符串的值;我检查整个字符串是否包含 '@xxx@' 子字符串,并为每个实例调用一个 replaceAll 方法,但我认为这是非常低效的。

非常感谢你!

TL;DR - 用不同的字符串替换字符串的子字符串的模式/匹配器是否比检查字符串是否包含子字符串并使用 String#replaceAll 更有效?如果是这样,我将如何处理?

最佳答案

这是 appendReplacement 的一个相对简单的例子:

// Prepare map of replacements
Map<String,String> 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.

关于Java 正则表达式字符串#replaceAll 替代,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41407648/

10-12 01:31
查看更多