The use of the shortest matching pattern in regular expressions

Source: Internet
Author: User
If there is a text, you just want to match the shortest possible, not the longest. This paper mainly introduces some relevant data about the usage of the shortest matching pattern in regular expressions.

Objective

Recently, I want to use regular expressions to crawl something out of the Web page, the content is not complex but there are a lot of problems. The following words do not say, come together to see the detailed introduction:

When we use regular expressions to match the first and last of a label, such as the start of a H1 in a match and the closing tag

Maybe a lot of people would write that.


/<.*h1>/g


But is that really possible?

Because the * match is 0 to more than the previous character, and it's a greedy match.

So what you get is going to be the result.


Obviously that's not what we want, so how do we change the greedy match to the smallest match?


/<.*?h1>/g


The above writing is possible, such as:


In fact, the principle should be very simple, because? is also a greedy match, and can only match 0 to 1,

So it will match to the end of the first one, thus blocking the matching of multiple greed.

The above content is the use of the shortest matching pattern in regular expressions, hoping to help everyone.

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.