欢迎来到代码驿站!

当前位置:首页 >

Javascript中使用exec进行正则表达式全局匹配时的注意事项

时间:2021-03-18 09:45:44|栏目:|点击:
本文就是介绍在使用 Javascript 中使用 exec 进行正则表达式全局匹配时的注意事项。
先看一下常见的用法:
复制代码 代码如下:

<script type="text/javascript">
var pattern = /http:\/\/([^\/\s]+)/;
alert(pattern.exec('http://www.codebit.cn')); // http://www.codebit.cn,www.codebit.cn
alert(pattern.exec('http://YITU.org')); // http://YITU.org,YITU.org
// 也可以直接写成 /http:\/\/([^/]+)/.exec('http://www.codebit.cn');
</script>

接下来看一下全局模式下的诡异事件:
复制代码 代码如下:

<script type="text/javascript">
var pattern = /http:\/\/([^\/\s]+)/g; // 使用了 g 修饰符
alert(pattern.exec('http://www.codebit.cn')); // http://www.codebit.cn,www.codebit.cn
alert(pattern.exec('http://YITU.org')); // 并没有返回期望的 http://YITU.org,YITU.org ,而是返回了 null
</script>

第二个语句并没有返回期望的结果,而是返回了 null ,这是因为:
在全局模式下,当 exec() 找到了与表达式相匹配的文本时,在匹配后,它将把正则表达式对象的 lastIndex 属性设置为匹配文本的最后一个字符的下一个位置。这就是说,您可以通过反复调用 exec() 方法来遍历字符串中的所有匹配文本。当 exec() 再也找不到匹配的文本时,它将返回 null,并把 lastIndex 属性重置为 0。
下面是正常的全局模式下的匹配方式:
复制代码 代码如下:

<script type="text/javascript">
var pattern = /http:\/\/([^\/\s]+)/g;
var str = "CodeBit.cn : http://www.codebit.cn | YITU.org : http://YITU.org";
var result;
while ((result = pattern.exec(str)) != null) {
alert("Result : " + result + " LastIndex : " + pattern.lastIndex);
}
//Result : http://www.codebit.cn,www.codebit.cn LastIndex : 34
//Result : http://YITU.org,YITU.org LastIndex : 67
</script>

从上面的代码我们可以看到,之所以出现第二段代码中的问题,影响因素是 lastIndex ,所以我们可以通过将 lastIndex 手动置 0 的方式来解决这个问题。
复制代码 代码如下:

<script type="text/javascript">
var pattern = /http:\/\/([^\/\s]+)/g; // 使用了 g 修饰符
alert(pattern.exec('http://www.codebit.cn')); // http://www.codebit.cn,www.codebit.cn
pattern.lastIndex = 0;
alert(pattern.exec('http://YITU.org')); // http://YITU.org,YITU.org
</script>

总结:
在全局模式下,如果在一个字符串中完成了一次模式匹配之后要开始检索新的字符串,就必须手动地把 lastIndex 属性重置为 0。

上一篇:Navicat添加外键详细操作步骤

栏    目:

下一篇:Powershell小技巧之通过EventLog查看近期电脑开机和关机时间

本文标题:Javascript中使用exec进行正则表达式全局匹配时的注意事项

本文地址:http://www.codeinn.net/misctech/83146.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有