Java String.replaceAll backreference with named groups

1.7k views Asked by At

How do you refer to named capture groups in Java's String.replaceAll method?

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

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.

1

There are 1 answers

0
Pshemo On BEST ANSWER

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

you should use ${nameOfCapturedGroup} which in your case would be ${render}.

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