RegExp.prototype.exec()
RegExp.prototype.exec()方法在一个指定的字符串中执行模式匹配。如果匹配成功,返回数组;否则返回null。如果程序只是为了判断字符串中是否有匹配模式,请调用RegExp.prototype.test()或String.prototype.search()以提升查询效率。
var regex1 = RegExp('foo*','g');
var str1 = 'table football, foosball';
var array1;
while ((array1 = regex1.exec(str1)) !== null) {
console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`);
// 输出: "Found foo. Next starts at 9."
// 输出: "Found foo. Next starts at 19."
}
语法
regexObj.exec(str)
参数
str
需要匹配模式的字符串。
返回值
如果匹配成功,RegExp.prototype.exec()函数返回一个数组并更新正则表达式对象的属性。返回的数组以匹配值作为第一项,随后每一项就是在这个匹配值中的捕获组。如果没有匹配成功,RegExp.prototype.exec()函数会返回null。
描述
先看下面的一个例子:
// 查找 "quick brown" 之后跟随"jumps",两者中可以是任意字符串(+?是非贪婪模式)
// "brown"和"jumps"为两个捕获组
// 忽略大小写
var re = /quick\s(brown).+?(jumps)/ig;
var result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog');
执行结果将会是如下所述:
(1)result
- result[0]:匹配值。result[0]=”Quick Brown Fox Jumps”;
- result[1],…[n]:根据正则表达式中对应捕获组,在匹配值中出现的值。result[1]=”Brown”,result[2]=”Jumps”;
- index:匹配值中第一个字符在整个字符串中的索引。result.index=4;
- input:整个字符串。result.input=” The Quick Brown Fox Jumps Over The Lazy Dog”;
(2)re
- lastIndex:下一次匹配执行起点的索引,也就是本次匹配值的最后一个字符索引+1。如果没有g修饰符,lastIndex永远是0。re.lastIndex=25;
- ignoreCase正则表达式中是否有i修饰符。re.ignoreCase=true;
- global:正则表达式中是否有g修饰符。re.global=true;
- multiline:正则表达式中是否有m修饰符。re.multiline=false;
- source:正则表达式文本。re.source=”quick\s(brown).+?(jumps)”;
示例
通过RegExp.prototype.exec()函数找到匹配项
如果正则表达式中包含g修饰符,你就可以通过循环多次执行RegExp.prototype.exec()函数来获取所有在字符串中匹配到的值。匹配的执行会根据正则表达式的lastIndex属性,来确定从什么位置开始匹配(RegExp.prototype.test()函数也会执行同样的规则)。请格外注意,如果lastIndex的值已经改变了,当传入不同的字符串作为RegExp.prototype.exec()函数的参数时,lastIndex并不会重置为零,而是使用上一次设置的lastIndex。
var myRe = /ab*/g;
var str = 'abbcdefabh';
var myArray;
while ((myArray = myRe.exec(str)) !== null) {
var msg = 'Found ' + myArray[0] + '. ';
msg += 'Next match starts at ' + myRe.lastIndex;
console.log(msg);
}
// Found abb. Next match starts at 3
// Found ab. Next match starts at 9
注意!
对于RegExp.prototype.exec()函数,执行时不要在for循环中声明正则表达式,这样会导致每个循环开始lastIndex都被重置为0,从而引起死循环。同时也要确保正则表达式包含g修饰符,没有g修饰符也会引起死循环,因为lastIndex永远是0。
直接调用
我们也可以直接用下面的方式调用RegExp.prototype.exec()函数:
var matches = /(hello \S+)/.exec('This is a hello world!');
console.log(matches[1]);
//输出:hello world!