Home >Java >javaTutorial >Java regular expression matching patterns (greedy, reluctant, possessive)

Java regular expression matching patterns (greedy, reluctant, possessive)

高洛峰
高洛峰Original
2017-01-09 16:19:101537browse

Greediness (Greediness): Maximum matching

X?, X*, X+, X{n,} is the maximum matching. For example, if you want to use "618b16d23a3ddab818f44e3be2c27e38" to match "aa34de1251f0d9fe1e645927f19a896e8aava fd273fcf5bcad3dfdad3c41bd81ad3e5abb", maybe the result you expect is to match "a34de1251f0d9fe1e645927f19a896e8", but the actual result will match Go to "a34de1251f0d9fe1e645927f19a896e8aava fd273fcf5bcad3dfdad3c41bd81ad3e5.

In Greediness mode, it will try to match as wide a range as possible until the entire content is matched. At this time, when it is found that the match cannot be successful, it will start to shrink back a little. Matching range until successful match

String test = "a<tr>aava </tr>abb ";
String reg = "<.+>";
System.out.println(test.replaceAll(reg, "###"));

Output: a

abb


Reluctant(Laziness) (reluctant): minimum match

X??,

In Reluctant mode, as long as the match is successful, it will no longer try 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


Different from Greediness, the content is matched twice in Reluctant mode

Possessive (possessive): exact match

X?+, X*+, X++, X{n,} + is a complete match. Add + after the Greediness pattern to become a complete match.

Possessive pattern has a certain similarity with Greediness, that is, it tries to match the largest range of content until the end of the content, but it is different from Greediness. Yes, exact matching no longer falls back to trying to match a smaller range

## Output: aa34de1251f0d9fe1e645927f19a896e8aava fd273fcf5bcad3dfdad3c41bd81ad3e5abb

For more Java regular expression matching patterns (greedy, reluctant, possessive) related articles, please pay attention to the PHP Chinese website


Statement:
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