javascript三种正则匹配

javascript中正则匹配有3个方法,match,exec,test。这些方法都跟字符串和RegExp对象有关。

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 属性的值。 

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.test(string)

  该方法最简单,在string中找到匹配regExp的字符串则返回true,没找到匹配的字符串则返回false

 string.match(regExp)

该方法比exec简单一些,因为它不用考虑regExp的lastIndex属性。同样,也需要分两种情况(全局匹配与非全局匹配)

 

match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。

该方法类似 indexOf() 和 lastIndexOf(),但是它返回指定的值,而不是字符串的位置。

<script type="text/javascript">

var str="Hello world!"
document.write(str.match("world") + "<br />")
document.write(str.match("World") + "<br />")
document.write(str.match("worlld") + "<br />")
document.write(str.match("world!"))

</script>
输出
world
null
null
world!
 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值