找回密码
 开放注册

QQ登录

只需一步,快速开始

微信登录

微信扫码,快速开始

搜索
查看: 1172|回复: 1

Javascript中正则表达式的全局匹配模式 /g

[复制链接]

739

主题

468

回帖

4307

牛毛

论坛管理员

狼群

积分
4347
发表于 2011-8-17 20:02:13 | 显示全部楼层 |阅读模式
先看一道JavaScript题目,据说是国内某知名互联网企业的JavaScript笔试题,如果对正则的全局匹配模式不了解的话可能会对下面的输出结果感到疑惑。


view plaincopy to clipboardprint?01.var str = "123#abc";   
02.var re = /abc/ig;   
03.console.log(re.test(str)); //输出ture   
04.console.log(re.test(str)); //输出false   
05.console.log(re.test(str)); //输出ture   
06.console.log(re.test(str)); //输出false  
var str = "123#abc";
var re = /abc/ig;
console.log(re.test(str)); //输出ture
console.log(re.test(str)); //输出false
console.log(re.test(str)); //输出ture
console.log(re.test(str)); //输出false

     在创建正则表达式对象时如果使用了“g”标识符或者设置它了的global属性值为ture时,那么新创建的正则表达式对象将使用模式对要将要匹配的字符串进行全局匹配。在全局匹配模式下可以对指定要查找的字符串执行多次匹配。每次匹配使用当前正则对象的lastIndex属性的值作为在目标字符串中开始查找的起始位置。lastIndex属性的初始值为0,找到匹配的项后lastIndex的值被重置为匹配内容的下一个字符在字符串中的位置索引,用来标识下次执行匹配时开始查找的位置。如果找不到匹配的项lastIndex的值会被设置为0。当没有设置正则对象的全局匹配标志时lastIndex属性的值始终为0,每次执行匹配仅查找字符串中第一个匹配的项。可以通下面的代码来查看在执行匹配相应的lastIndex 属性的值。

view plaincopy to clipboardprint?01.var str = "123#abc";   
02.var re = /abc/ig;   
03.console.log(re.test(str)); //输出ture   
04.console.log(re.lastIndex); //输出7   
05.console.log(re.test(str)); //输出false   
06.console.log(re.lastIndex); //输出0   
07.console.log(re.test(str)); //输出ture   
08.console.log(re.lastIndex); //输出7   
09.console.log(re.test(str)); //输出false   
10.console.log(re.lastIndex); //输出0  
var str = "123#abc";
var re = /abc/ig;
console.log(re.test(str)); //输出ture
console.log(re.lastIndex); //输出7
console.log(re.test(str)); //输出false
console.log(re.lastIndex); //输出0
console.log(re.test(str)); //输出ture
console.log(re.lastIndex); //输出7
console.log(re.test(str)); //输出false
console.log(re.lastIndex); //输出0

关于RegExp.prototype.exec(str)方法和String.prototype.math(rgExp)方法

    正则对象的test方法返回值为true或flase,在仅需要检测目标字符串与指定模式是否匹配,但不需要获取匹配内容时这个方法非常有用。当需要获取匹配结果时就需要用RegExp类型的exec(str)方法或String类型的match(rgExp)方法。

    RegExp.prototype.exec(str)方法返回NULL或返会一个数组,在数组的第0个元素存放的是在字符串str中查找到的匹配内容,1到n个元素返回的是在模式中使用括号"()"指定的子匹配项的内容。

    在没有使用全局标志时String.prototype.math(rgExp)方法和RegExp.prototype.exec(str)的行为类似。当设置了全局匹配标志时String.prototype.math(rgExp)方法返回的数组项元素0到n中包含了所有匹配到的项不包含子匹配项。这时可以使用RegExp.$1..$9获取9个子匹配。

739

主题

468

回帖

4307

牛毛

论坛管理员

狼群

积分
4347
 楼主| 发表于 2011-8-17 20:33:49 | 显示全部楼层
刚看下论坛广告太多!
您需要登录后才可以回帖 登录 | 开放注册

本版积分规则

帮助|Archiver|小黑屋|通信管理局专项备案号:[2008]238号|NB5社区 ( 皖ICP备08004151号;皖公网安备34010402700514号 )

GMT+8, 2025-4-25 05:57 , Processed in 0.137893 second(s), 35 queries .

Powered by Discuz! X3.5

快速回复 返回顶部 返回列表