views:

366

answers:

3

I have this code, and I want to know, if I can replace only groups (not all pattern) in Java regex. Code:

 //...
 Pattern p = Pattern.compile("(\\d).*(\\d)");
    String input = "6 example input 4";
    Matcher m = p.matcher(input);
    if (m.find()) {

        //Now I want replace group one ( (\\d) ) with number 
       //and group two (too (\\d) ) with 1, but I don't know how.

    }
+2  A: 

Add a third group by adding parens around ".*", then replace the subsequence with "number" + m.group(2) + "1". e.g.:

String output = m.replaceFirst("number" + m.group(2) + "1");
Matt Kane
Actually, Matcher supports the $2 style of reference, so m.replaceFirst("number$21") would do the same thing.
Michael Myers
Oh, even better.
Matt Kane
+3  A: 

Use $n (where n is a digit) to refer to captured subsequences in replaceFirst(...). I'm assuming you wanted to replace the first group with the literal string "number" and the second group with the value of the first group.

Pattern p = Pattern.compile("(\\d)(.*)(\\d)");
String input = "6 example input 4";
Matcher m = p.matcher(input);
if (m.find()) {
    // replace first number with "number" and second number with the first
    String ouput = m.replaceFirst("number $2$1");
}

Consider ([^d]+) for the second group instead of (.*). * is a greedy matcher, and will at first consume the last digit. The matcher will then have to backtrack when it realizes the final (\d) has nothing to match, before it can match to the final digit.

Chadwick
Thanks a lot...
wokena
A: 

You can use matcher.start() and matcher.end() methods to get the group positions. So using this positions you can easily replace any text.

ydanneg