javascript 正则表达式的组、全局、RegExp.exec()和string.match()区别

前言

javascript的正则表达式,基本用法可以参考这个 ;在会了基本用法后,有几个概念一定要注意,组、全局、RegExp.exec和String.match的区别。

全局

全局是标志是否全局匹配,通俗点说就是后一次匹配从上次匹配处往后匹配。比如

var reg = /.at/g;
var str ="1at,2at,3at";
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));

结果

[ '1at', index: 0, input: '1at,2at,3at' ]
[ '2at', index: 4, input: '1at,2at,3at' ] //本次匹配,从1at后边往后匹配
[ '3at', index: 8, input: '1at,2at,3at' ] //本地匹配,从2at后边往后匹配
null

对应的我们去掉全局匹配

var reg = /.at/;
var str ="1at,2at,3at";
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));
[ '1at', index: 0, input: '1at,2at,3at' ] //每次匹配都是从最开始搜寻
[ '1at', index: 0, input: '1at,2at,3at' ]
[ '1at', index: 0, input: '1at,2at,3at' ]
[ '1at', index: 0, input: '1at,2at,3at' ]

组主要用来获取匹配结果,首先匹配全局正则,然后匹配第1个子表达式、第2个子表达式,依次类推….

var reg = /(.a)t/;
var str ="1at,2at,3at";
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));

首先匹配.at ,然后再匹配 .a, 所以每次匹配有两个

[ '1at', '1a', index: 0, input: '1at,2at,3at' ]
[ '1at', '1a', index: 0, input: '1at,2at,3at' ]
[ '1at', '1a', index: 0, input: '1at,2at,3at' ]
[ '1at', '1a', index: 0, input: '1at,2at,3at' ]

全局&&组

学完了全局和组,再来个复杂点的正则

var reg = /(.a)t/g;
var str ="1at,2at,3at";
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));
[ '1at', '1a', index: 0, input: '1at,2at,3at' ]
[ '2at', '2a', index: 4, input: '1at,2at,3at' ]
[ '3at', '3a', index: 8, input: '1at,2at,3at' ]
null

RegExp.exec() VS String.match()

正则表达式的exec()与字符串的match()很像,

不带全局表达式

不带全局标志时,两者一样

var reg = /(.a)t/;
var str ="1at,2at,3at";
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));

console.log("--------------------------");

console.log(str.match(reg));
[ '1at', '1a', index: 0, input: '1at,2at,3at' ]
[ '1at', '1a', index: 0, input: '1at,2at,3at' ]
[ '1at', '1a', index: 0, input: '1at,2at,3at' ]
[ '1at', '1a', index: 0, input: '1at,2at,3at' ]
--------------------------
[ '1at', '1a', index: 0, input: '1at,2at,3at' ]

全局表达式

带全局表达式时,string.match()一次返回表达式、子表达式匹配结果,但不返回所以及输入项;

var reg = /(.a)t/g;
var str ="1at,2at,3at";
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));

console.log("--------------------------");

console.log(str.match(reg));
[ '1at', '1a', index: 0, input: '1at,2at,3at' ]
[ '2at', '2a', index: 4, input: '1at,2at,3at' ]
[ '3at', '3a', index: 8, input: '1at,2at,3at' ]
null
--------------------------
[ '1at', '2at', '3at' ]

你可能感兴趣的:(javascript,regular,expression,javascript)