3

$1 値を整数のように使用したい。
アイデアは、originaltext のすべての数値を同等の配列値に置き換えて、新しいテキストを作成することです。
以下の望ましい結果は、「これは DBValue4、これは DBValue2、これは DBValue7 です」である必要があります。
また、これらの後方参照を後で使用するために保存する方法はありますか?

String[] values = {"DBValue0","DBValue1","DBValue2","DBValue3","DBValue4","DBValue5","DBValue6","DBValue7","DBValue8","DBValue9","DBValue10"};
String originaltext = "This is 4, This is 2, This is 7";
text = originaltext.replaceAll("(\\d)","$1");
// want something like
text = originaltext.replaceAll("(\\d)",values[$1]);
//or
text = originaltext.replaceAll("(\\d)",values[Integer.parseInt("$1")]);
4

1 に答える 1

4

Pattern次のMatcherように使用できます。

public static void main(String[] args) throws Exception {
    final String[] values = {"DBValue0", "DBValue1", "DBValue2", "DBValue3", "DBValue4", "DBValue5", "DBValue6", "DBValue7", "DBValue8", "DBValue9", "DBValue10"};
    final String originaltext = "This is 4, This is 2, This is 7";
    final Pattern pattern = Pattern.compile("(?<=This is )\\d++");
    final Matcher matcher = pattern.matcher(originaltext);
    final StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        System.out.println(matcher.group());
        final int index = Integer.parseInt(matcher.group());
        matcher.appendReplacement(sb, values[index]);
    }
    matcher.appendTail(sb);
    System.out.println(sb);
}

出力:

4
2
7
This is DBValue4, This is DBValue2, This is DBValue7

編集

OPのコメントに加えて、OPは「名前」が配列の名前で、「インデックス」がその配列内の要素のインデックスであるString形式の sを置き換える必要があるようです。{name, index}

Mapこれは、 を使用してアレイをその名前に ping し、Map<String, String[]>次に をPatternキャプチャしてから を使用することで簡単に実現できnameますindex

public static void main(String[] args) throws Exception {
    final String[] companies = {"Company1", "Company2", "Company3"};
    final String[] names = {"Alice", "Bob", "Eve"};
    final String originaltext = "This is {company, 0}, This is {name, 1}, This is {name, 2}";
    final Map<String, String[]> values = new HashMap<>();
    values.put("company", companies);
    values.put("name", names);
    final Pattern pattern = Pattern.compile("\\{([^,]++),\\s*+(\\d++)}");
    final Matcher matcher = pattern.matcher(originaltext);
    final StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        System.out.println(matcher.group(1));
        System.out.println(matcher.group(2));
        final int index = Integer.parseInt(matcher.group(2));
        matcher.appendReplacement(sb, values.get(matcher.group(1))[index]);
    }
    matcher.appendTail(sb);
    System.out.println(sb);
}

出力:

company
0
name
1
name
2
This is Company1, This is Bob, This is Eve
于 2013-07-24T13:50:01.413 に答える