これは、他の同様の質問へ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質問は正規表現を書く方法ではなく、複数の 'replaceAll()'呼び出しを使わずに複数の異なる '@ keyword @'パターンを 'keyword'に依存する値に置き換える方法です。トリックは、['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ありがとうございます。これは、文字列を一度しか検索する必要がない非常に興味深い方法です。 StringBuilderではなくStringBufferを使用した理由はありますか?また、置換可能な〜50の異なる部分文字列があれば、少し冗長になりませんか? –