Java Regular Expression matching mode (greedy, barely, occupy), java Regular Expression

Source: Internet
Author: User

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

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.