RegExp.prototype.exec() - JavaScript 编辑

The exec() method executes a search for a match in a specified string. Returns a result array, or null.

JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g. /foo/g or /foo/y). They store a lastIndex from the previous match. Using this internally, exec() can be used to iterate over multiple matches in a string of text (with capture groups), as opposed to getting just the matching strings with String.prototype.match().

A newer function has been proposed to simplify matching multiple parts of a string (with capture groups): String.prototype.matchAll().

If you are executing a match to find true or false, use RegExp.prototype.test() method or String.prototype.search() instead.

Syntax

regexObj.exec(str)

Parameters

str
The string against which to match the regular expression.

Return value

If the match succeeds, the exec() method returns an array (with extra properties index and input; see below) and updates the lastIndex property of the regular expression object. The returned array has the matched text as the first item, and then one item for each parenthetical capture group of the matched text.

If the match fails, the exec() method returns null, and sets lastIndex to 0.

Description

Consider the following example:

// Match "quick brown" followed by "jumps", ignoring characters in between
// Remember "brown" and "jumps"
// Ignore case
let re = /quick\s(brown).+?(jumps)/ig;
let result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog');

The following table shows the results for this script:

ObjectProperty/IndexDescriptionExample
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.

result[1] === "Brown"

result[2] === "Jumps"

indexThe 0-based index of the match in the string.4
inputThe original string that was matched against.The Quick Brown Fox Jumps Over The Lazy Dog
relastIndex

The index at which to start the next match.

If g is absent, this will always be 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 across multiple lines.false
sourceThe text of the pattern.quick\s(brown).+?(jumps)

Examples

Finding successive matches

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). Note that the lastIndex property will not be reset when searching a different string, it will start its search at its existing lastIndex .

For example, assume you have this script:

let myRe = /ab*/g;
let str = 'abbcdefabh';
let myArray;
while ((myArray = myRe.exec(str)) !== null) {
  let msg = 'Found ' + myArray[0] + '. ';
  msg += 'Next match starts at ' + myRe.lastIndex;
  console.log(msg);
}

This script displays the following text:

Found abb. Next match starts at 3
Found ab. Next match starts at 9

Warning: Do not place the regular expression literal (or RegExp constructor) within the while condition!

It will create an infinite loop if there is a match, due to the lastIndex property being reset upon each iteration.

Also, be sure that the global flag ("g") is set, or it will also cause an infinite loop.

Using exec() with RegExp literals

You can also use exec() without creating a RegExp object explicitly:

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

This will log a message containing 'hello world!'.

Specifications

Specification
ECMAScript (ECMA-262)
The definition of 'RegExp.exec' in that specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:97 次

字数:10122

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文