Deeply understand the analysis of greedy mode and non-greedy mode of JS regular expressions

不言
Release: 2018-07-11 09:45:37
Original
2186 people have browsed it

This article mainly introduces the analysis of greedy mode and non-greedy mode for in-depth understanding of JS regular expressions. It has certain reference value. Now I share it with you. Friends in need can refer to it

The greedy mode

mentioned regular quantifiers before, but the quantifiers will bring about the problem of whichshould be matched.

The following regular expression:

\d{3,6}
Copy after login

This regular expression matches 3 to 6 numbers, but when this regular expression is used to match the

12345678string , should it match three numbers, six numbers, or neither?

You can try it first:

let text = '12345678' let reg = /\d{3,6}/g text.replace(reg, 'X') // X78
Copy after login

You can see that this regular expression replaces the six numbers

123456withX, that is, in normal mode , the regular expression will match as many matches as possible.

Under normal circumstances, regular expressions adopt greedy mode, that is, match as many as possible.

Non-greedy mode

However, sometimes we need the regular expression to match as few as possible, that is, once a successful match is made, no more attempts will be made. This is the non-greedy mode. So, how to enter non-greedy mode?

The method is very simple, just add

?after the quantifier.

let text = '12345678' let reg = /\d{3,6}?/g text.replace(reg, 'X') // X45678
Copy after login

It can be found that in non-greedy mode, this regular pattern only matches

123, which is the minimum match.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

In-depth understanding of the analysis of quantifiers of JS regular expressions

In-depth understanding of the analysis of JS regular expressions Analysis of predefined classes and boundaries

The above is the detailed content of Deeply understand the analysis of greedy mode and non-greedy mode of JS 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 admin@php.cn
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!