regExp.exec
regExp.exec
exec()
方法在一个指定字符串中执行一个搜索匹配。返回一个结果数组或null
。
如果你只是为了判断是否匹配(true或 false),可以使用RegExp.test()
方法,或者String.search()
方法。
语法
regexObj.exec(str)
参数
str
要匹配正则表达式的字符串。
返回值
如果匹配成功,exec
() 方法返回一个数组,并更新正则表达式对象的属性。返回的数组将完全匹配成功的文本作为第一项,将正则括号里匹配成功的作为数组填充到后面。
如果匹配失败,exec() 方法返回null
。
描述
考虑以下示例:
// Match "quick brown" followed by "jumps", ignoring characters in between
// Remember "brown" and "jumps"
// Ignore case
var re = /quick\s(brown).+?(jumps)/ig;
var result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog'
下表列出这个脚本的返回值:
Object | Property/Index | Description | Example |
---|---|---|---|
result | 0 | The full string of characters matched | Quick Brown Fox Jumps |
1, ...n | The parenthesized substring matches, if any. The number of possible parenthesized substrings is unlimited. | 1 = Brown 2 = Jumps | |
index | The 0-based index of the match in the string. | 4 | |
input | The original string. | The Quick Brown Fox Jumps Over The Lazy Dog | |
re | lastIndex | The index at which to start the next match. When "g" is absent, this will remain as 0. | 25 |
ignoreCase | Indicates if the "i" flag was used to ignore case. | true | |
global | Indicates if the "g" flag was used for a global match. | true | |
multiline | Indicates if the "m" flag was used to search in strings across multiple lines. | false | |
source | The text of the pattern. | quick\s(brown).+?(jumps) |
示例
查找所有匹配
当正则表达式使用 "g
" 标志时,可以多次执行 exec
方法来查找同一个字符串中的成功匹配。当你这样做时,查找将从正则表达式的 lastIndex
属性指定的位置开始。(test()
也会更新 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
构造器)放在while
条件表达式里。由于每次迭代时lastIndex
的属性都被重置,如果匹配,将会造成一个死循环。并且要确保使用了'g'标记来进行全局的匹配,否则同样会造成死循环。
结合 RegExp 字面量使用 exec()
你也可以直接使用exec()
而不是创建一个 RegExp
对象:
var matches = /(hello \S+)/.exec('This is a hello world!'
console.log(matches[1]
运行上面的代码,控制台会输出"hello world!" 字符串。
规范
Specification | Status | Comment |
---|---|---|
ECMAScript 3rd Edition (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.2. |
ECMAScript 5.1 (ECMA-262)The definition of 'RegExp.exec' in that specification. | Standard | |
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'RegExp.exec' in that specification. | Standard | |
ECMAScript Latest Draft (ECMA-262)The definition of 'RegExp.exec' in that specification. | Living Standard | |
浏览器兼容性
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |