Sarang Shinde
Sarang Shinde

Reputation: 737

Java Regex pattern.matcher Understanding

Consider Following code

import java.util.regex.*;

public static void main(String[] args) {
    String str = "Suneetha N.=9876543210, Pratish Patil=9898989898";
    Pattern pattern = Pattern.compile("(\\w+)(\\s\\w+)(=)(\\d{10})");
    Matcher matcher = pattern.matcher(str);
    String newStr = matcher.replaceAll("$4:$2,$1");
    System.out.println(newStr);
}

Output of above code is

Suneetha N.=9876543210, 9898989898: Patil,Pratish   

I am not able to understand what is use of matcher.replaceAll("$4:$3,$1") and how it works and produces this output. Please provide your suggestion on it.

Upvotes: 2

Views: 69

Answers (1)

Hrabosch
Hrabosch

Reputation: 1583

You have

"(\\w+)(\\s\\w+)(=)(\\d{10})" 

regex and imagine that it will create a GROUPS for founded string. In this example it is

Pratish Patil=9898989898 

and here are groups by regex:

(\\w+) => Pratish        $1
(\\s\\w+) => Patil       $2
(=) => =                 $3
(\\d{10}) => 9898989898  $4

Then you said that you want to replaceAll with this regex by this new ordering where $number defined a group. So you replacing

Pratish Patil=9898989898 

by new group order with : and ,.

$4:$2,$1 -> 9898989898:Patil,Pratish. 

You didnt use $3 group, where is =.

Upvotes: 3

Related Questions