Java文字列が評価キーで正規表現パターンを置き換えます

ご多幸を祈る :

私はこのような入力文字列を持っています

I want to go to {places} where {things} are happening.

{場所}と{}物事の値(すなわち、最初、私はすべてのキーのニーズを交換する何かを見つけるし、それらの値を計算し、その後、元の文字列でそれらを置き換える)なまけて計算されています。

私はすべてのキーを見つけることができていますし、以下のコードを使用してそれらを取り除きます。

public class Temp {
    private static final Pattern betweenCurlyBracesMatcher = Pattern.compile("\\{(.*?)\\}");

    public static void main(String args[]) {
        System.out.println(resolve2("hello {world} from {here}"));
    }

    public static String resolve2(String input) {
        Map<String, String> keyValueMap = new HashMap<>();
        Matcher matcher = betweenCurlyBracesMatcher.matcher(input);
        while (matcher.find()) {
            String key = matcher.group(1);
            if (!keyValueMap.containsKey(key)) {
                keyValueMap.put(key, computeValueForKey(key));
            }
        }
        for (Map.Entry<String, String> entry : keyValueMap.entrySet()) {
            input = input.replace("{" + entry.getKey() + "}", entry.getValue());  // << ugly code here
        }
        return input;
    }

    private static String computeValueForKey(String key) {
        return "new" + key;
    }
}

私はと満足していません

input = input.replace("{" + entry.getKey() + "}", entry.getValue());

私は私の正規表現を変更するたびに、それが意味するので、私はこのロジックを更新する必要があります。この問題へのよりエレガントな解決策はあります。


入力こんにちは{世界} {ここ}から

出力 newhereからハローのNewWorld


入力 Iは、{}物事が起こっている{場所}に行きたいです。

出力は、私はnewthingsが起こっているnewplacesに行きたいです。

ティムBiegeleisen:

あなたは使用すべきであるMatcher#appendReplacementMatcher#appendTailここにAPIを:

Map<String, String> keyValueMap = new HashMap<>();
keyValueMap.put("places", "to America");
keyValueMap.put("things", "events");
String input = "I want to go to {places} where {things} are happening.";
Pattern pattern = Pattern.compile("\\{(.*?)\\}");
Matcher matcher = pattern.matcher(input);
StringBuffer buffer = new StringBuffer();

while(matcher.find()) {
    matcher.appendReplacement(buffer, keyValueMap.get(matcher.group(1)));
}
matcher.appendTail(buffer);
System.out.println(buffer.toString());

この版画:

I want to go to to America where events are happening.

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=363861&siteId=1