Usage of shortest matching pattern in regular expressions

小云云
Release: 2023-03-17 19:32:01
Original
4048 people have browsed it

If there is a text, you only want to match the shortest possible one, not the longest one. This article mainly introduces you to the relevant information about the usage of the shortest matching pattern in regular expressions.

Preface

Recently, I wanted to use regular expressions to grab something from a web page. The content was not complicated, but many problems arose. . Not much to say below, let’s take a look at the detailed introduction:

When we use regular expressions to match the beginning and end of a tag, such as matching

hello world

The opening and closing tags of h1 in

maybe many people will write like this


/<.*h1>/g
Copy after login


But like this Is it really possible?

Because the * matching character matches zero or more of the previous character, and it is a greedy matching

, so what you get will be the following result.


Obviously this is not what we want, so how to change greedy matching into minimum matching,


/<.*?h1>/g
Copy after login


The above writing method is enough, as shown below:


In fact, the principle should be very simple, because? Also Greedy matching, and can only match 0 to 1,

, so it will end when it matches the first one, thus preventing * from matching multiple greedy ones.

The above content is the usage of the shortest matching pattern in regular expressions. I hope it can help everyone.

Related recommendations:

PHP regular expression collection

Detailed explanation of commonly used functions in php regular expressions

Summary of regular expressions commonly used in php forms

The above is the detailed content of Usage of shortest matching pattern in regular expressions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!