java - 使用正则表达式中的反向引用动态替换文本

标签 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")]);

最佳答案

您可以使用 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

关于java - 使用正则表达式中的反向引用动态替换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17835757/

相关文章:

java - 如何优化这个循环?

java - java中的阶乘递归 "visualized"

ruby - 仅使用一次 Ruby 正则表达式 gsub

Python正则表达式匹配字符

python - 从 Python 中的正则表达式模式获取多个匹配项

javascript - 一个简单的 javascript 正则表达式反向引用

java - AlertDialog 不从内部类显示

java - 如何使mysql数据库在客户端计算机(桌面应用程序)上运行?

regex - 如何捕获重复捕获组中每个组的组号

regex - 是否有可能找到具有反向引用的独占匹配项(在或组语句中)?