Regular Expression (regex) greedy mode, lazy mode use method, regular expression regex

Source: Internet
Author: User

Regular Expression (regex) greedy mode, lazy mode use method, regular expression regex

Regular Expression greedy match mode, which is often prone to errors for beginners. Sometimes you need to match the content of a code segment and find that the matching is inconsistent with the desired content. It was found that it had something to do with the greedy mode. The following is an example:

What is greedy mode?
The strings include

1. start and end of h3, and "

2. Any character can appear in the middle. The number can be 0 or more. The regular expression can be :. *, ". "represents any character. The default mode does not match the line feed." * "duplicates the first character 0 or multiple.

3. The final result is as follows: "

The two results are the same. This is what we don't want to get. We want to start matching from the left and the first appearance

What is laziness?
Since the above several types indicate the number of repeated characters, the metacharacters are greedy by default. If we need a minimum length match, that is, the lazy mode, how do we write a regular expression? In fact, the common method in a regular expression is to add "?" to indicate repeated metacharacters "?" Character. The above regular expression can be written as: "

The lazy mode matches the string we need.

Conclusion: Regular Expression, which indicates the number of repeated string metacharacters ,'?, +, *, {} 'Will select greedy mode by default, and the maximum length will match the string. to switch to lazy mode, just add "?" You can switch to non-Greedy mode (lazy mode ).

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.