Today used to regular expression of lazy match, because the beginning is not very understanding, so a problem tangled up a day, really understand it is not difficult.
Example: A string "ABCDAKDJD"
regex= "A.*?d"; Lazy Match
Regex2= "A.*d"; Greedy match
public static void Main (string[] args) {
int count = 0;
Scanner sc = new Scanner (system.in);
String str = Sc.next ();
String str = "ABCDAKDJD";
String regex= "A.*?d";
Pattern p = pattern.compile (regex);
Matcher m = p.matcher (str);
while (M.find ()) {
count++;
System.out.println (M.group ());
}
The number of System.out.println ("ABCDE" appears in the string "+str+" is "+count+");
}
Results:
Abcd
Akd
ABCDE occurs 2 times in string ABCDAKDJD
Here is the lazy match, the match to meet the conditions of ABCD stopped this match, will not interfere with the continuation of the match.
When you change the regex= "A.*?d" to regex= "A.*d"
Results:
Abcdakdjd
ABCDE occurs 1 times in string ABCDAKDJD
Here is greedy match, as the name implies, very greedy, to maximize the occupancy of the string.
The above two, one is try to match the shortest string, one is to match the longest string.