This article brings an explanation of regular laziness and greed. I hope it will be helpful to everyone.
exec - > Regular capture
Every time you capture, the default match is performed first. If there is no successful match, The captured result is null; we can capture only if there is matching content;
Captured content format
1. Captured content Is an array. The first item in the array is the content captured by the current regular expression.
Index: The index position where the captured content starts in the string.
Input: The captured original string
reg = /\d+/ str = 'woshi2016ni2017' res =
var res = reg.exec(str); console.log(res) // ['2016',index:5,input:'woshi2016ni2017']
2. Characteristics of regular capture
1) Lazy Properties -> Each time exec is executed, only the first matching content is captured. Without any processing, even if multiple captures are performed, the first matching content is still captured.
lastIndex: is the position where the search starts in the string for each regular capture. The default value is 0
2) How to solve laziness Sexuality? Add a modifier "g"
at the end of the regular expression Modifiers: g, i, m
global(g): Global matching
## ignoreCase(i): Ignore case matching
multiline(m):Multiline matching
var reg = /\d/g;
var str = 'woshi2016ni2017';
console.log(reg.lastIndex)
console.log(reg.exec(str))
3) Write your own program to get all the content captured by the regular expression (don’t forget to add g)
##
var reg = /\d+/g;var str = 'aswofde2015xsewde2016awdefer2017';var ary = [];var res = reg.exec(str);while(res){
ary.push(res[0])
res = reg.exec(str);
}
console.log(ary)//[2015,2016,2017]
5) How to solve the greedy nature of the regular pattern -> after the quantifier metacharacter add one? Just
var reg = /\d+?/g;var str = 'aswofde2015xsewde2016awdefer2017';
console.log(reg.exec(str));
Place A
ordinarymetacharacter followed by represents 0-1 occurrences of /\d?/ -> The number may or may not appear Putting it after the
metacharacter of aquantifier is greedy when canceling the capture 3. The match method in the string -> Match everything with the regular expression The characters of
are obtained var reg = /\d+?/g;var str = 'aswofde2015xsewde2016awdefer2017';var ary = str.match(reg);//[2,0,1,5,2,0,1,6,2,0,1,7]
The above is the detailed content of An explanation of regular laziness and greed. For more information, please follow other related articles on the PHP Chinese website!