Home > Java > javaTutorial > body text

Example analysis of greedy pattern matching of regular expressions in Java programs

黄舟
Release: 2017-01-20 11:10:58
Original
1588 people have browsed it

Greedy mode is also called maximum matching. X?, /tr>abb", maybe the result you are expecting is to match "", but the actual result will match "aava ". 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"]
Copy after login

java aspku.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:

Output:

Example 2:

Output:

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 (m.sbmmt.com)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!