RegExp.prototype.exec()

概述

exec() 方法为指定的一段字符串执行搜索匹配操作。它的返回值是一个数组或者 null 。

如果你仅仅是为了知道是否匹配,可以使用 RegExp.test() 方法,或者 String.search() 方法。

语法

regexObj.exec(str)

参数

str
这个字符串对应它匹配的正则表达式。

返回值

If the match succeeds, the exec method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.

If the match fails, the exec method returns null.

如果匹配成功,exec 方法将返回一个数组并更新正则表达式中属性值。

如果匹配失败,exec 方法将返回 null 。

描述

思考下面的例子:

// Match one d followed by one or more b's followed by one d
// Remember matched b's and the following d
// Ignore case
var re = /d(b+)(d)/ig;
var result = re.exec("cdbBdbsbz");

下面的表格展示这个脚本的返回值:

对象 属性/索引 描述 例子
result [0] The last matched characters dbBd
[1], ...[ n ] The parenthesized substring matches, if any. The number of possible parenthesized substrings is unlimited. [1] = bB
[2] = d
index The 0-based index of the match in the string. 1
input The original string. cdbBdbsbz
re lastIndex The index at which to start the next match. 5
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 line. false
source The text of the pattern. d(b+)(d)

例子

例子1:连续查找匹配

If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test() will also advance the lastIndex property). For example, assume you have this script:

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

注意:不要把正则表达式字面量(或者正则表达式构造器)放在 while 条件语句里。由于每次迭代时 lastIndex 的属性都被重置,如果匹配,将会造成一个死循环。

例子2:在RegExp 字面量中使用 exec()

你也可以直接使用 exec() 而不是创建一个 RegExp 对象:

var matches = /(hello \S+)/.exec('This is a hello world!');
alert(matches[1]);

运行上面的代码,会弹出一个内容为 "hello world!" 的对话框。

规范

Specification Status Comment
ECMAScript 3rd Edition. Implemented in JavaScript 1.2 Standard Initial definition.
ECMAScript Language Specification 5.1th Edition (ECMA-262) Standard  
ECMAScript Language Specification 6th Edition (ECMA-262) Draft  

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

参照

Document Tags and Contributors

Contributors to this page: LinusYu
最后编辑者: LinusYu,