Greedy pattern matching of regular expressions in Java programs

Greedy mode:

The quantity indicator defaults to greedy mode unless otherwise indicated. The expression of greedy mode will match until it cannot match. If you find that the matching result of the expression does not match the expected result, it is likely because - you think the expression will only match the first few characters, but in fact it is a greedy pattern, so it will match all the time. Greed and non greed, plus? Non greedy:

By default, the Java regular expression uses the greedy greedy matching pattern, which is the longest matching of this type (. *). If the shortest matching is required, it is changed to (. *?) That is, the barely matched pattern. Principle analysis: if it is a greedy matching pattern, the regular expression engine will match until the end of the string. When the matching is false, it will backward find the penultimate matching position and return the matching result. If it is a reluctantly matching pattern, the regular expression engine will match the character at the end of the pattern, and then go back, If the match is found to be false, it will be traced back to the last location where the fallback match is found to be true, and the result will be returned. Look at the code: Example 1:

Output:

Example 2:

Output:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>