Java Regex String#replaceAll Alternative [英] Java Regex String#replaceAll Alternative

查看:304
本文介绍了Java Regex String#replaceAll Alternative的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在设法用Pattern / Matcher实例替换多个String#replaceAll调用的方法,希望它比我在String中替换文本的当前方法更快,但我不确定如何去做。

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 method of replacing text in a String, but I'm not sure how to go about it.

以下是我想要操作的字符串示例:

Here is an example of a String that I want to manipulate:

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

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

As you can see, there are multiple @ characters with 3 characters in between; this will always be the case. If I wanted to replace every instance of '@xxx@' (where xxx can be any lowercase letter or digit from 0 to 9), what would the most efficient way to go about it be? Currently I'm storing a Map where its keys are '@xxx@' substrings, and the values are what I want to replace that specific substring with; I check if the whole String contains the '@xxx@' substring, and call a replaceAll method for each instance, but I imagine this is pretty inefficient.

非常感谢你很多!

TL; DR - 使用不同的String替换String的子串的Pattern / Matcher是否比检查String是否包含子串更有效串#的replaceAll?如果是这样,我该怎么办呢?

TL;DR - Would a Pattern/Matcher to replace a substring of a String with a different String be more efficient than checking if the String contains the substring and using String#replaceAll? If so, how would I go about it?

推荐答案

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

演示。

这篇关于Java Regex String#replaceAll Alternative的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆