I would like to replace a match with the number/index of the match.
Is there way in java regex flavour to know which match number the current match is, so I can use String.replaceAll(regex, replacement)
?
Example: Replace [A-Z]
with itself and its index:
Input: fooXbarYfooZ
Output: fooX1barY2fooZ3
ie, this call:
"fooXbarXfooX".replaceAll("[A-Z]", "$0<some reference to the match count>");
should return "fooX1barY2fooZ3"
Note: I'm looking a replacement String that can do this, if one exists.
Please do not provide answers involving loops or similar code.
Edited:
I'll accept the most elegant answer that works (even if it uses a loop). No current answers
actually work.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…