简体   繁体   中英

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.

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 = .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM