简体   繁体   English

Java String.replaceAll带有命名组的反向引用

[英]Java String.replaceAll backreference with named groups

How do you refer to named capture groups in Java's String.replaceAll method? 您如何在Java的String.replaceAll方法中引用命名的捕获组?

As a simplified example of what I'm trying to do, say I have the regex 作为我要尝试做的简化示例,说我有正则表达式

\{(?<id>\d\d\d\d):(?<render>.*?)\}

which represents a tag in a string. 代表字符串中的标签。 There can be multiple tags in a string, and I want to replace all tags with the contents of the "render" capture group. 一个字符串中可以有多个标签,我想用“渲染”捕获组的内容替换所有标签。

If I have a string like 如果我有一个像

String test = "{0000:Billy} bites {0001:Jake}";

and want to get a result like "Billy bites Jake" , I know I can accomplish my goal with 并希望获得像"Billy bites Jake"这样的结果,我知道我可以通过

test.replaceAll(tagRegex, "$2")

but I would like to be able to use something like 但我希望能够使用类似

test.replaceAll(tagRegex, "$render")`

Is there a way to do this? 有没有办法做到这一点? Using "$render" I get IllegalArgumentException: Illegal group reference . 使用"$render"我得到IllegalArgumentException: Illegal group reference

Based on https://blogs.oracle.com/xuemingshen/entry/named_capturing_group_in_jdk7 基于https://blogs.oracle.com/xuemingshen/entry/named_capturing_group_in_jdk7

you should use ${nameOfCapturedGroup} which in your case would be ${render} . 您应该使用${nameOfCapturedGroup} ,在您的情况下为${render}

DEMO: DEMO:

String test = "{0000:Billy} bites {0001:Jake}";
test = test.replaceAll("\\{(?<id>\\d\\d\\d\\d):(?<render>.*?)\\}", "${render}");
System.out.println(test);

Output: Billy bites Jake 输出: Billy bites Jake

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM