3

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 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.