Greedy mode (greedy):
The quantifier defaults to greedy mode unless otherwise indicated. The expression of the greedy pattern will always match until it cannot be matched. If you find that the result of an expression match is not what you expected, it's probably because--you think the expression matches only the first few characters, and it's actually a greedy pattern, so it's always going to match.
Greed and non-greed, plus? Not greed:
var s = ' 1023000 '. Match (/(\d+) (0*)/);
s
["1023000", "1023000", "" "]
var s = ' 1023000 '. Match (/^ (\d+) (0*) $/);
s
["1023000", "1023000", ""]
var s = ' 1023000 '. Match (/^ (\d+?) (0*) $/);
s
["1023000", "1023", "M"]
var s = ' 1023000 '. Match (/(\d+?) (0*)/);
S
["10", "1", "0"]
The default Java regular expression is the greedy greedy match pattern is both the longest match for this type (. *), and if the shortest match is required, change to (. *?) That is, a barely matched pattern.
Principle Analysis:
in the case of a greedy match pattern, the regular expression engine will always match to the end of the string, and when the match is false, the
Backtracking, backward to find the first match, return the match result
In the case of a grudging match, the regular expression engine matches the character at the end of pattern, then steps back, finds the match to be false, and goes back to the location where the nearest match to the fallback is true, returning the result.
Look at the code:
Example One:
public void Test51 () {
String str = "aaa\" bbb\ "ccc\" ddd\ "eee";
System.out.println (str);
str = str.replaceall ("\" (. *) \ "", "@");
System.out.println (str);
Output:
AAA "BBB" CCC "DDD" Eee
aaa@eee
Case TWO:
@Test public
void Test52 () {
String str = "aaa\" bbb\ "ccc\" ddd\ "eee";
System.out.println (str);
str = str.replaceall ("\" (. *?) \"", "@");
System.out.println (str);
Output:
AAA "BBB" CCC "DDD" Eee
aaa@ccc@eee