Is there any way to replace a regexp with modified content of capture group?
Example:
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher(text);
resultString = regexMatcher.replaceAll("$1"); // *3 ??
And I'd like to replace all occurrence with $1 multiplied by 3.
edit:
Looks like, something's wrong 🙁
If I use
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher("12 54 1 65");
try {
String resultString = regexMatcher.replaceAll(regexMatcher.group(1));
} catch (Exception e) {
e.printStackTrace();
}
It throws an IllegalStateException: No match found
But
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher("12 54 1 65");
try {
String resultString = regexMatcher.replaceAll("$1");
} catch (Exception e) {
e.printStackTrace();
}
works fine, but I can't change the $1 🙁
edit:
Now, it's working 🙂
Best Answer
How about:
To get the first match, use
#find()
. After that, you can use#group(1)
to refer to this first match, and replace all matches by the first maches value multiplied by 3.And in case you want to replace each match with that match's value multiplied by 3:
You may want to look through
Matcher
's documentation, where this and a lot more stuff is covered in detail.