Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to correctly use the shortest matching pattern in regular expressions

Shulou Source: shulou.com Published: 2022-06-02 15:10:44 10月09日 Update

How to correctly use the shortest matching pattern in regular expressions? In view of this problem, this article introduces the corresponding analysis and answers in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

When we use regular expressions to match the beginning and end of a tag, such as matching the beginning and closing tags of H2 in hello world

Maybe a lot of people would write like this.

/ / g

But is this really okay?

Because the * match matches zero or more of the previous character, and it matches greedily

So what you get will be the following result.

Obviously this is not what we want, so how to replace the greedy match with the smallest match?

/ / g

The above is fine, as shown in the following picture:

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

So it ends when it matches to the first one, thus preventing the greed of multiple matches.

This is the answer to the question on how to correctly use the shortest matching pattern in regular expressions. I hope the above content can be of some help to you, if you still have a lot of doubts to be solved. You can follow the industry information channel for more related knowledge.

Tags: Greed regular expression problem pattern multiple time more label face help solution easy minimum easy content Writing principle character Boy Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi MySQL NVidia macOS OPPO Reno