在正则表达式中使用反向引用来动态替换文本

时间:2013-07-24 13:41:09

标签: java regex backreference replaceall

我想像整数一样使用$ 1值 我们的想法是用原始文本替换所有数字和等效的数组值,并创建一个新文本 下面想要的结果应该是“这是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")]);

1 个答案:

答案 0 :(得分:4)

您可以像这样使用PatternMatcher

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形式的{name, index},其中“name”是数组的名称,“index”是元素的索引在那个数组中。

通过Map使用Map<String, String[]>将数组ping到其名称,然后使用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