Replacing Java Regex with Capture Group

Is there a way to replace regex with the changed contents of the capture group?

Example:

Pattern regex = Pattern.compile("(\\d{1,2})"); Matcher regexMatcher = regex.matcher(text); resultString = regexMatcher.replaceAll("$1"); // *3 ?? 

And I would like to replace all occurrences with $ 1 multiplied by 3.

change

Something seems to be 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 $ 1 :(

change

Now it works :)

+67
java regex
Aug 14 '09 at 10:29
source share
4 answers

What 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 with the first value of the magicians multiplied by 3.

And in case you want to replace each match with this match 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 can view the Matcher documentation for details on this and more.

+74
Aug 14 '09 at 10:33
source share
Answer to

earl gives you a solution, but I thought I would add that the problem is what causes your IllegalStateException . You call group(1) without first calling the matching operation (e.g. find() ). This is not necessary if you just use $1 , since replaceAll() is a matching operation.

+11
Aug 14 '09 at 11:21
source share

Source: java-implementation-of-rubys-gsub

Using:

 // Rewrite an ancient unit of length in SI units. String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") { public String replacement() { float inches = Float.parseFloat(group(1)); return Float.toString(2.54f * inches) + " cm"; } }.rewrite("a 17 inch display"); System.out.println(result); // The "Searching and Replacing with Non-Constant Values Using a // Regular Expression" example from the Java Almanac. result = new Rewriter("([a-zA-Z]+[0-9]+)") { public String replacement() { return group(1).toUpperCase(); } }.rewrite("ab12 cd efg34"); System.out.println(result); 

Implementation (revised):

 import static java.lang.String.format; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class Rewriter { private Pattern pattern; private Matcher matcher; public Rewriter(String regularExpression) { this.pattern = Pattern.compile(regularExpression); } public String group(int i) { return matcher.group(i); } public abstract String replacement() throws Exception; public String rewrite(CharSequence original) { return rewrite(original, new StringBuffer(original.length())).toString(); } public StringBuffer rewrite(CharSequence original, StringBuffer destination) { try { this.matcher = pattern.matcher(original); while (matcher.find()) { matcher.appendReplacement(destination, ""); destination.append(replacement()); } matcher.appendTail(destination); return destination; } catch (Exception e) { throw new RuntimeException("Cannot rewrite " + toString(), e); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(pattern.pattern()); for (int i = 0; i <= matcher.groupCount(); i++) sb.append(format("\n\t(%s) - %s", i, group(i))); return sb.toString(); } } 
+1
Dec 31 '16 at 9:50
source share

Java 9 offers Matcher.replaceAll() which accepts a replacement function:

 resultString = regexMatcher.replaceAll(m -> String.valueOf(Integer.parseInt(m.group()) * 3)); 
0
Mar 28 '19 at 20:07
source share



All Articles