欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-05-27 13:24:43
先给大家说下js正则表达式中的g到底是什么意思 g是global的缩写啊! 就是匹配全部可匹配结果, 如果你不带g,在正则过程中,字符串是从左至右匹配的,如果匹配成功...

先给大家说下js正则表达式中的g到底是什么意思

g是global的缩写啊!

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

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

例如:

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模式的区别,具体代码如下所示:

<!doctype html> 
<html> 
<head lang="en"> 
  <meta charset="utf-8"> 
  <title>mischen</title> 
  <script> 
    //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 
    } 
  </script> 
</head> 
<body> 
</body> 
</html> 

以上所述是小编给大家介绍的js中使用正则表达式g模式和非g模式的区别,希望对大家有所帮助