js里面正则表达式的exec函数与字符串的match详解
说的越多有时候还越迷糊,一句话总结exec函数和match函数的区别:
调用方式不同,exec函数是正则表达式对象的函数,参数为字符串,格式reg.exec(str),返回值为数组;
而match是字符串的函数,参数为正则表达式对象,格式:str.match(regexp),需要注意的一点是,当regexp对象带g:此时返回值不提供与子表达式匹配的文本的信息,当regexp对象不带g:返回值跟执行一次exec的结果是一样的。
下面我们来看个例子就明白了:
<script type="text/javascript"> var str="some files need to be protectd,like: auth.conf pwd.properties task.sh"; var reg=/\s*\w+(\.\w+)\s*/gi; var matchArr; var ret=""; while((matchArr=reg.exec(str))!=null){ //matchArr:reg不含分组时下标为0的就存放整个匹配到的内容。有分组的时候就依次往后存,即下标为1的存第一个分组的内容。。。 console.log(matchArr);//比如其中一条结果为: // ["pwd.properties ", ".properties", index: 47, input: "some files need to be protectd,like: auth.conf // pwd.properties task.sh"] console.log("exec函数返回的数组长度:"+matchArr.length);//==2:非数字下标相当于数组属性,不计入个数 //正则表达式有个lastIndex属性为下一次开始从哪个位置开始匹配 ret+="在下标"+matchArr.index+"处找到"+matchArr[0]+",下一个从"+reg.lastIndex+"处开始\n"; } console.log(ret); console.log("---------------------------"); var a=str.match(reg); console.log(a);//结果:[" auth.conf ", "pwd.properties ", "task.sh"] reg=/\s*\w+(\.\w+)\s*/i; a=str.match(reg); console.log(a);//结果:[" auth.conf ", ".conf", index: 36, input: "some files need to be protectd,like: auth.conf pwd.properties task.sh"] //说明,如果不加g进行全局匹配,只匹配到第一个后就不继续往下进行匹配了 </script>
执行结果如下所示: