Java Regular expression matching pattern [greedy type, reluctance type, possessive type]

Source: Internet
Author: User

Greediness (greedy type): Maximum match

X, x*, x+, X{n,} are the maximum matches. For example you want to use "<.+>" to match "A<tr>aava </tr>abb", perhaps the result you expect is to match "<tr>", but the actual result will match to "<tr>aava </ Tr>.

In the greediness mode, the match will be as large as possible until the entire content is matched, and when the match is found to be unsuccessful, the fallback narrowing the match until the match is successful

String test = "A<tr>aava </tr>abb"= "<.+>""# # #");

Output: a## #abb

Reluctant (laziness) (barely): Minimum match

X??、 x*, x+?, X{n,}? Is the minimum match, in fact x{n,m}? and X{n}? Some superfluous. Add after greediness mode? is the smallest match.

In reluctant mode, attempts to match a larger range of content are no longer attempted as long as the match succeeds

String test = "A<tr>aava </tr>abb"= "<.+?>""# # #");

Output: a## #aava # # #abb

Unlike greediness, the content is matched in reluctant mode two times

Possessive (possessive): Exact match

x?+, x*+, x + +, x{n,}+ are exact matches, and adding + after greediness mode is an exact match.

The possessive pattern has a certain similarity to greediness, which is to match the maximum range of content as much as possible until the content ends, but unlike greediness, the exact match no longer rolls back the attempt to match a smaller range.

String test = "A<tr>aava </tr>abb"= "<.++>"= "<tr>"= "<tr>" "###""###"));

Output: A<tr>aava </tr>abb

###

Java Regular expression matching pattern [greedy type, reluctance type, possessive type]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.