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 :)
How about:
if (regexMatcher.find()) { resultString = regexMatcher.replaceAll( String.valueOf(3 * Integer.parseInt(regexMatcher.group(1)))); }
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:
Pattern p = Pattern.compile("(\\d{1,2})"); Matcher m = p.matcher("12 54 1 65"); StringBuffer s = new StringBuffer(); while (m.find()) m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1)))); System.out.println(s.toString());
You may want to look through Matcher
's documentation, where this and a lot more stuff is covered in detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With