Greedy mode:
The quantity indicator defaults to greed mode unless otherwise indicated. The expressions of greedy patterns will continue to match until they cannot. If you find that the result of the expression matching does not match the expected one, it is very likely that it is because - you think the expression will only match the first few characters, but in fact it is a greedy pattern, so it will continue to match.
Greed and non-greed, plus? is non-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["10", "1", "0"]
Java regular expressions use the greedy greedy matching pattern by default. It is the longest match of this type (.*). If the shortest match is required, it will be changed to (.*?) that is, it is a barely match pattern.
Principle analysis:
If it is a greedy matching pattern, the regular expression engine will match until the end of the string. When the match is false, it will backwards and find the last matching position to return the matching result. If it is a barely match pattern, the regular expression engine will match the character at the end of the pattern, and then take a step back, find that the match is false, and then trace back to the position where the most recent match found in the fallback is true, returning the result.
Look at the code:
Example 1:
public void test51(){ String str = "aaa/"bbb/"ccc/"dd/"eee"; System.out.println(str); str = str.replaceAll("/"(.*)/"", "@"); System.out.println(str); } Output:
aaa"bb"cc"ddd"eeeaaa@eee
Example 2:
@Test public void test52(){ String str = "aaa/"bbb/"ccc/"dd/"eee"; System.out.println(str); str = str.replaceAll("/"(.*?)/"", "@"); System.out.println(str); } Output:
aaa"bb"cc"ddd"eeeaaa@ccc@eee