Regular expression (regex) greedy mode, lazy mode use method _ Regular expression

Source: Internet
Author: User
Tags regular expression

Regular expression greedy matching pattern, for beginners, often prone to error. Sometimes you need to match a piece of code to find that the match is inconsistent with what you want. It turns out to be related to greedy patterns. As follows, let's look at the following example:

What is greedy mode
The string has: "

1, H3 the beginning and the end, "

2, the middle can appear any character, the number can be 0 or more, regular expression can be used:. *, "." Represents any character, the default mode does not match line wrapping, and "*" repeats the preceding character 0 or more.

3, finally we consider the result will be: "

2 kinds of results are the same, this is what we do not want, we want to start from the left, the first occurrence of

What is lazy mode
Since several of the above indicate the number of characters to repeat, the meta characters are by default greedy mode. If we need a minimum length match, which is lazy mode, how do we write regular expressions? In fact, the regular expression inside the general method is, in the expression of metacharacters characters, followed by a more "?" Characters can be. The above regular expression can be written as: "

Lazy mode, it matches up to the string we need.

Summary: Regular expressions, representing string repeats, '?, +,*,{} ' by default will select greedy mode, the maximum length matching string, and to switch to lazy mode, just in the meta character, followed by a "?" 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.