If I have a regex with a capturing group, e.g. foo(_+f)
. If I match this against a string and want to replace the first capturing group in all matches with baz
so that
foo___f blah foo________f
is converted to:
foobaz blah foobaz
There doesn't appear to be any easy way to do this using the standard libraries. If I use Matcher.replaceAll() this will replace all matches of the entire pattern and convert the string to
baz blah baz
Obviously I can just iterate through the matches, store the start and end index of each capturing group, then go back and replace them, but is there an easier way?
Thanks,
Don
Best Answer
I think you want something like this?
Here you simply replace the entire match with
"baz"
, but the match uses lookbehind to ensure that_+f
is preceded byfoo
.See also
If lookbehind is not possible (perhaps because the length is not finite), then simply capture even what you're NOT replacing, and refer to them back in the replacement string.
So here we're effectively only replacing what
\2
matches.