首页 > 编程技术 > js

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

发布时间:2017-4-3 10:00

先给大家说下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模式的区别,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

标签:[!--infotagslink--]

您可能感兴趣的文章: