I would like to replace a match with the number/index of the match.
Is there way in java to know which match number the current match is, so I can use only replaceAll(regex, replacement)
to inject the count of each match into the result?
Example: Replace [A-Z]
with itself and its index:
Input: fooXbarYfooZ
Output: fooX1barY2fooZ3
eg this:
"fooXbarXfooX".replaceAll("[A-Z]", "$0<some reference to the match count>");
should return "fooX1barY2fooZ3"
Note: I seek a replacement String within a single invocation of replaceAll()
(or similar method) that does the entire job.
Answers that use more than just a single method call, eg wrapping replacement operations in a for
loop, do not answer the question.