首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

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

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

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模式的区别,具体代码如下所示:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!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>

返回列表