java - Regex replace with the count of the match -


i replace match number/index of match.

is there way in java regex flavour know match number current match is, can use string.replaceall(regex, replacement)?

example: replace [a-z] , index:

input:  fooxbaryfooz output: foox1bary2fooz3 

ie, call:

"fooxbarxfoox".replaceall("[a-z]", "$0<some reference match count>"); 

should return "foox1bary2fooz3"


note: i'm looking replacement string can this, if 1 exists.


please not provide answers involving loops or similar code.


edited:

i'll accept elegant answer works (even if uses loop). no current answers
work.

iterating on input string required looping 1 way or other inevitable. standard api not implement method implementing loop loop either have in client code or in third party library.


here how code btw:

public abstract class matchreplacer {      private final pattern pattern;      public matchreplacer(pattern pattern) {         this.pattern = pattern;     }      public abstract string replacement(matchresult matchresult);      public string replace(string input) {          matcher m = pattern.matcher(input);          stringbuffer sb = new stringbuffer();          while (m.find())             m.appendreplacement(sb, replacement(m.tomatchresult()));          m.appendtail(sb);          return sb.tostring();     } } 

usage:

public static void main(string... args) {     matchreplacer replacer = new matchreplacer(pattern.compile("[a-z]")) {         int = 1;         @override public string replacement(matchresult m) {              return "$0" + i++;         }     };     system.out.println(replacer.replace("fooxbarxfoox")); } 

output:

foox1barx2foox3 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -