您当前的位置: 首页 >  正则表达式

任磊abc

暂无认证

  • 1浏览

    0关注

    182博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

JS中使用正则表达式g模式和非g模式的区别

任磊abc 发布时间:2020-05-15 17:26:12 ,浏览量:1

g是global的缩写啊!

就是匹配全部可匹配结果,

如果你不带g,在正则过程中,字符串是从左至右匹配的,如果匹配成功就不再继续向右匹配了,如果你带g,它会重头到尾的把正确匹配的字符串挑选出来

例如:

1

2

3

4

5

var str = 'aaaaaaaa'

var reg1 = /a/

var reg2 = /a/g

str.match(reg1)  // 结果为:["a", index: 0, input: "aaaaaaaa"]

str.match(reg2)  // 结果为:["a", "a", "a", "a", "a", "a", "a", "a"]

js正则表达式g模式与非g模式的区别,具体代码如下所示:

 
 
 
   
  mischen 
   
    //js中使用正则表达式 
    function test(){ 
      //生成正则表达式对象; 
      // 在g模式下,正则表达式对象的exec和test方法,依赖 正则表达式对象的lastIndex属性,而lastIndex会根据我们exec 
      // 和test的执行 发生偏移  如果没有相应匹配  lastIndex 重归0 
      //在非g模式下,正则表达式对象的exec和test方法, lastIndex 不会发生偏移 
      //exec方法 如果正则表达式中 有分组  第一个返回的是 匹配到的字符串 后面是根据分组分别返回的匹配的 字符串 
      var reg=new RegExp("\\d+[a-z]+","ig"); //字符串里 \ 表示转译 
      var str="123abc123def"; 
      alert(reg.lastIndex);//0 
      alert(reg.exec(str));//123abc 
      alert(reg.lastIndex);//6 
      alert(reg.test(str));//true 
      alert(reg.lastIndex);//12 
    } 
   // test(); 
    test1(); 
    function test1(){ 
      //非g模式下使用 exec 和test 
      var reg=new RegExp("\\d+[a-z]+","i"); 
      var str="123abc123def"; 
//      alert(reg.lastIndex);//0 
//      alert(reg.exec(str));//123abc 
//      alert(reg.lastIndex);//0 
//      alert(reg.test(str));//true 
//      alert(reg.lastIndex);//0 
//      alert(reg.exec(str));//123abc 
//      alert(reg.lastIndex);//0 
//      alert(reg.test(str));//true 
//      alert(reg.lastIndex);//0 
      var reg=new RegExp("(\\d+)([a-z]+)","i"); 
      alert(reg.exec(str));//123abc,123,abc 
      alert(reg.exec(str));//123abc,123,abc 
    } 
   
 
 
 
 

 

关注
打赏
1656830895
查看更多评论
立即登录/注册

微信扫码登录

0.0373s