match 方法

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

function match(rgExp : RegExp) : Array

参数

  • rgExp
    必选。包含正则表达式模式和适用标志的 Regular Expression 对象的实例。也可以是包含正则表达式模式和标志的变量名或字符串。

备注

如果 match 方法没有找到匹配,将返回 null。如果找到匹配,则 match 方法返回一个数组,并将更新全局 RegExp 对象的属性以反映匹配结果。

match 方法返回的数组有三个属性:inputindexlastIndexInput 属性包含整个被搜索的字符串。Index 属性包含了在整个被搜索字符串中匹配的子字符串的位置。LastIndex 属性包含了前一次匹配中最后一个字符的下一个位置。

如果没有设置全局标志 (g),数组的零元素包含整个匹配,而第 1 到第 n 个元素包含了匹配中曾出现过的任一个子匹配。此行为与没有设置全局标志的 exec 方法的行为相同。如果设置了全局标志,则元素 0 到 n 中包含所有出现的匹配。

示例

下面的示例阐释了 match 方法的用法。

function MatchDemo(){
   var r, re;         //Declare variables.
   var s = "The rain in Spain falls mainly in the plain";
   re = /ain/i;    //Create regular expression pattern.
   r = s.match(re);   //Attempt match on search string.
   return(r);         //Return first occurrence of "ain".
}

本示例阐释设置了 g 标志的 match 方法的用法。

function MatchDemo(){
   var r, re;         //Declare variables.
   var s = "The rain in Spain falls mainly in the plain";
   re = /ain/ig;      //Create regular expression pattern.
   r = s.match(re);   //Attempt match on search string.
   return(r);         //Return array containing all four
                      // occurrences of "ain".
}

下列代码行阐释了 match 方法如何用于字符串。

var r, re = "Spain";
r = "The rain in Spain".replace(re, "Canada");

要求

版本 3

请参见

exec 方法 | RegExp 对象 | replace 方法 | search 方法 | test 方法

适用于:String 对象