", but the actual result will match "
Home >Java >javaTutorial >Example analysis of greedy pattern matching of regular expressions in Java programs
Greedy mode is also called maximum matching. X?, /tr>abb", maybe the result you are expecting is to match "a34de1251f0d9fe1e645927f19a896e8", but the actual result will match "a34de1251f0d9fe1e645927f19a896e8aava fd273fcf5bcad3dfdad3c41bd81ad3e5". Let's take a closer look. Use of greedy mode.
Greedy mode (Greedy):
The quantity indicator defaults to greedy mode, unless otherwise indicated. The expression in greedy mode will continue to match until it cannot be matched. If you find that the expression matching results are not as expected, it is most likely because - you thought the expression would only match the first few characters, but in fact it is a greedy pattern, so it will continue to match.
Greedy and non-greedy, plus? is non-greedy:
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", "000"] var s = '1023000'.match(/(\d+?)(0*)/); s ["10", "1", "0"]
java 7d245e93741ad1afebce7f65d66b428faspku.com/kaifa/zhengze/" target="_blank">regular The expression uses the greedy greedy matching mode by default, which is the longest match of this type (.*). If the shortest match is required, it is changed to (.*?), which is the reluctant matching mode.
Principle analysis:
If it is a greedy matching mode, the regular expression engine will match until the end of the string. When the match is false, it will find the first matching position from the bottom through
backtracking. Return the matching result
If the pattern is barely matched, the regular expression engine will match the character that matches the end position of the pattern, and then go one step further back and find that the match is false, and then go back to find the most recent match of the fallback. The position of true returns the result.
Look at the code:
Example 1:
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
Example 2:
@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
The above is an example Analyze the content of greedy pattern matching of regular expressions in Java programs. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!