Java Regular Expression matching mode (greedy, barely, occupy), java Regular Expression
Greediness (Greedy): maximum matching
X? , X *, X +, X {n,} is the maximum match. For example, if you want to use "<. +> "match" a <tr> aava </tr> abb ". Maybe you want to match" <tr> ", however, the actual result matches "<tr> aava </tr>.
In Greediness mode, the matching will be as wide as possible until the entire content is matched. If the matching fails, the system will roll back and narrow the matching until the matching is successful.
String test = "a<tr>aava </tr>abb ";String reg = "<.+>";System.out.println(test.replaceAll(reg, "###"));
Output: a ### abb
Reluctant (Laziness) (barely): minimum matching
X ?? , X *? , X ++? , X {n ,}? Is the minimum match. In fact, X {n, m }? And X {n }? It is redundant. Add after Greediness mode? The minimum match.
In Reluctant mode, as long as the matching is successful, no more attempts will be made to match a wider range of content.
String test = "a<tr>aava </tr>abb ";String reg = "<.+?>";System.out.println(test.replaceAll(reg, "###"));
Output: a ### aava ### abb
Unlike Greediness, the Reluctant mode matches the content twice.
Possessive (occupancy type): exact match
X? +, X * +, X ++, and X {n,} + are completely matched. After adding + to Greediness mode, the matching is complete.
The Possessive mode has a certain similarity with Greediness, that is, it tries to match the content in the maximum range until the content ends. However, unlike Greediness, the exact match does not roll back and try to match a smaller range.
String test = "a<tr>aava </tr>abb ";String reg = "<.++>";String test2 = "<tr>";String reg2 = "<tr>";System.out.println(test.replaceAll(reg, "###"));System.out.println(test2.replaceAll(reg2, "###"));
Output: a <tr> aava </tr> abb