zl程序教程

您现在的位置是:首页 >  后端

当前栏目

js正则表达式中test,exec,match方法的区别说明

JS方法正则表达式 说明 区别 match test exec
2023-06-13 09:15:17 时间

js正则表达式中test,exec,match方法的区别说明

test
test返回Boolean,查找对应的字符串中是否存在模式。
varstr="1a1b1c";
varreg=newRegExp("1.","");
alert(reg.test(str));//true


exec
exec查找并返回当前的匹配结果,并以数组的形式返回。
varstr="1a1b1c";
varreg=newRegExp("1.","");
vararr=reg.exec(str);
如果不存在模式,则arr为null,否则arr总是一个长度为1的数组,其值就是当前匹配项。arr还有三个属性:index当前匹配项的位置;lastIndex当前匹配项结束的位置(index+当前匹配项的长度);input如上示例中input就是str。


exec方法受参数g的影响。若指定了g,则下次调用exec时,会从上个匹配的lastIndex开始查找。
varstr="1a1b1c";
varreg=newRegExp("1.","");
alert(reg.exec(str)[0]);
alert(reg.exec(str)[0]);
上述两个输出都是1a。现在再看看指定参数g:
varstr="1a1b1c";
varreg=newRegExp("1.","g");
alert(reg.exec(str)[0]);
alert(reg.exec(str)[0]);
上述第一个输出1a,第二个输出1b。


match
match是String对象的一个方法。
varstr="1a1b1c";
varreg=newRegExp("1.","");
alert(str.match(reg));
match这个方法有点像exec,但:exec是RegExp对象的方法;math是String对象的方法。二者还有一个不同点,就是对参数g的解释。
如果指定了参数g,那么match一次返回所有的结果。
varstr="1a1b1c";
varreg=newRegExp("1.","g");
alert(str.match(reg));
//alert(str.match(reg));//此句同上句的结果是一样的
此结果为一个数组,有三个元素,分别是:1a、1b、1c。

JavaScript中经常用到正则表达式,而正则表达式中经常用到Match和Test这两个函数,当然还有Exec.这里以代码实例来区分它们之间的不同吧.

MatchExample

复制代码代码如下:

varstr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
varregexp=/[A-E]/gi;
varrs=str.match(regexp);
//rs=Array("A","B","C","D","E","a","b","c","d","e");

TestExample
复制代码代码如下:

varstr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
varregexp=/[A-E]/gi;
varrs=regexp.test(str);
//rs=true;boolean

ExcExample
复制代码代码如下:
varstr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
varregexp=/[A-E]/gi;
varrs;
while((rs=regexp.exec(str))!=null)
{
   document.write(rs);
   document.write(regexp.lastIndex);
   document.write("<br/>");
}

OUTPUT
---------------------------------
A   1
B  2
C  3
D  4
E  5
a  27
b  28
c  29
d  30
e  31


Another  ExcExample
复制代码代码如下:
varregexp=/ab*/g;
varstr="abbcdefabh";
varrs;
while((rs=regexp.exec(str))!=null)
{
   document.write(rs);
   document.write(regexp.lastIndex);
   document.write("<br/>");
}

OUTPUT
---------------------------------
abb  3
ab    9