這是previous answer更加動態版本到另一個類似的問題。
這裏是幫助您搜索任何@[email protected]
的方法。它們不一定是3個字符。
private static String replace(String input, Map<String, String> replacement) {
StringJoiner regex = new StringJoiner("|", "@(", ")@");
for (String keyword : replacement.keySet())
regex.add(Pattern.quote(keyword));
StringBuffer output = new StringBuffer();
Matcher m = Pattern.compile(regex.toString()).matcher(input);
while (m.find())
m.appendReplacement(output, Matcher.quoteReplacement(replacement.get(m.group(1))));
return m.appendTail(output).toString();
}
測試
Map<String,String> replacement = new HashMap<>();
replacement.put("bla", "hello,");
replacement.put("red", "world!");
replacement.put("Hold", "wait");
replacement.put("Better", "more");
replacement.put("a?b*c", "special regex characters");
replacement.put("foo @ bar", "with spaces and the @ boundary character work");
System.out.println(replace("@[email protected] is a @[email protected] @[email protected] text", replacement));
System.out.println(replace("But @[email protected], this can do @[email protected]!", replacement));
System.out.println(replace("It can even handle @a?b*[email protected] without dying", replacement));
System.out.println(replace("Keyword @foo @ [email protected] too", replacement));
輸出
hello,This is a world!line hello,of text
But wait, this can do more!
It can even handle special regex characters without dying
Keyword with spaces and the @ boundary character work too
「的replaceAll」已經正則表達式;學會使用正則表達式。 –
@BoristheSpider問題不在於如何編寫正則表達式,而是如何使用依賴關鍵字的值替換多個不同的'@ keyword @'模式,而不使用多個'replaceAll()'調用。技巧是['appendReplacement()'](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#appendReplacement-java.lang.StringBuffer-java。 lang.String-)和['appendTail()'](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#appendTail-java.lang.StringBuffer- )'匹配器'的方法。 – Andreas
@Andreas謝謝你,這是一個非常有趣的方式,只需要一次搜索字符串即可。你有使用StringBuffer而不是StringBuilder的原因嗎?另外,如果我有大約50種不同的子字符串可以被替換,它會不會略爲冗長? –