Regular expressions-greedy and non-greedy match __ regular expressions

Source: Internet
Author: User

+ greedy match vs. non-greedy matching

Greedy match
By default, regular expressions use the longest matching principle (also known as the greedy matching principle).
For example: to match "Zo?" in "Zoom" Replaced by "R" and the result of the replacement is "ROM". If you want to replace the section "zo*" in "Zoom" with "R", the replacement result is "RM".

Non-greedy match
When the character. followed by other qualifiers (*, +,. , {n}, {n,}, {n,m}), the matching pattern becomes the shortest matching principle (also known as the non-greedy matching principle).
For example: In the string "Fooood", "fo+?" Matches only the "fo" section, while "fo+" matches the "foooo" section.

When a regular expression contains a qualifier that can accept duplicates, the usual behavior is to match as many characters as possible (in order for the entire expression to be matched). Take this expression as an example: A.*b, which will match the longest string starting with a and ending with B. If you use it to search for Aabab, it will match the entire string aabab. This is called a greedy match.

Sometimes we need more lazy matching, which is to match as few characters as possible. The qualifier given above can be converted to lazy matching mode, just add a question mark after it. So. * is meant to match any number of repetitions, but with minimal repetition in the premise that the entire match succeeds. Now look at the lazy version of the example:

A.*?b matches the shortest, starting with a string ending with B. If you apply it to Aabab, it will match AaB and AB.

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.