Using (Java) regular expressions, I'm trying to execute Matcher.replaceAll
to replace only a specific group, not all matches. Can you tell me how to do it in Java?
static void main(String[] args) {
String exp = "foofoobarfoo";
exp = Pattern
.compile("foo(foo)")
.matcher(exp)
.replaceAll(gr -> "911" + gr.group(1) + "911");
System.out.println(exp);
}
I'm expecting: foo911foo911barfoo
The actual result: 911foo911barfoo
(Because replaceAll
applied the replacement string to all matches, namely the groups gr.group(0) (foo foo bar foo) and gr.group(1) (foo bar foo). And it is necessary to replace only gr.group(1), without gr.group(0)).
How to select a specific group to replace in a string from a regular expression?
You need to capture the first foo
, too:
exp = Pattern
.compile("(foo)(foo)")
.matcher(exp)
.replaceAll(gr -> gr.group(1) + "911" + gr.group(2) + "911");
See the Java demo online.
Since there are two capturing groups now - (foo)(foo)
- there are now two gr.group()
s in the replacement: gr.group(1) + "911" + gr.group(2) + "911"
.