By default, pattern matching is greedy, which means that the matcher returns the longest match possible. For example, applying the pattern A. * C
To Abcabca
Matches Abcabc
Rather
Than the shorter ABC
. To do nongreedy matching, a question mark must be added to the quantifier.
Example, the pattern A .*? C
Will find the shortest match possible.
// Greedy quantifiers string match = find (". * C "," abcabc "); // abcabc match = find (". + "," abcabc "); // abcabc // nongreedy quantifiers match = find (". *? C "," abcabc "); // ABC match = find (" A. +? "," Abcabc "); // ABC // returns the first substring in input that matches the pattern. // returns NULL if no match found. public static string find (string patternstr, charsequence input) {pattern = pattern. compile (patternstr); matcher = pattern. matcher (input); If (matcher. find () {return matcher. group ();} return NULL ;}
Note: This article Reprinted from: http://www.zsm8.com/book/java_Exa/java.util.regex/Greedy.html