在线文档教程

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'

下表列出这个脚本的返回值:

ObjectProperty/IndexDescriptionExample
result0The full string of characters matchedQuick Brown Fox Jumps
1, ...n The parenthesized substring matches, if any. The number of possible parenthesized substrings is unlimited.1 = Brown 2 = Jumps
indexThe 0-based index of the match in the string.4
inputThe original string.The Quick Brown Fox Jumps Over The Lazy Dog
relastIndexThe index at which to start the next match. When "g" is absent, this will remain as 0.25
ignoreCaseIndicates if the "i" flag was used to ignore case.true
globalIndicates if the "g" flag was used for a global match.true
multilineIndicates if the "m" flag was used to search in strings across multiple lines.false
sourceThe 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!" 字符串。

规范

SpecificationStatusComment
ECMAScript 3rd Edition (ECMA-262)StandardInitial 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

浏览器兼容性

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support(Yes)(Yes)(Yes)(Yes)(Yes)(Yes)

FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support(Yes)(Yes)(Yes)(Yes)(Yes)(Yes)(Yes)