exec 方法

使用正则表达式模式对字符串执行搜索,并返回一个包含该搜索结果的数组。

function exec(str : String) : Array

实参

  • str
    必选。 执行搜索的 String 对象或字符串文本。

备注

如果 exec 方法没有找到匹配,将返回 null。 如果找到匹配,则 exec 方法返回一个数组,并将更新全局 RegExp 对象的属性以反映匹配结果。 数组元素 0 包含了完整的匹配,而元素 1 到 n 包含的是匹配中出现的任意一个子匹配。 这相当于没有设置全局标志 (g) 的 match 方法的行为。

如果为正则表达式设置了全局标志,则 execlastIndex 值指示的位置开始搜索字符串。 如果没有设置全局标志,则 exec 忽略 lastIndex 的值,从字符串的起始位置开始搜索。

exec 方法返回的数组有三个属性:inputindexlastIndex.Input 属性包含整个被搜索的字符串。 Index 属性包含了在整个被搜索字符串中匹配的子字符串的位置。 lastIndex 属性中包含了匹配中最后一个字符的下一个位置。

示例

下面的示例阐释了 exec 方法的用法:

var src = "The quick brown fox jumps over the lazy dog.";

// Create regular expression pattern with a global flag.
var re = /\w+/g;

// Get the next word, starting at the position of lastindex.
var arr;
while ((arr = re.exec(src)) != null)
{
    print (arr.index + "-" + arr.lastIndex + " " + arr[0]);
}

// Output:
//  0-3 The
//  4-9 quick
//  10-15 brown
//  16-19 fox
//  20-25 jumps
//  26-30 over
//  31-34 the
//  35-39 lazy
//  40-43 dog

要求

版本 3

应用于:

正则表达式对象

请参见

参考

match 方法

RegExp 对象

search 方法

test 方法

概念

正则表达式语法