Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3843253
  • 博文数量: 146
  • 博客积分: 3918
  • 博客等级: 少校
  • 技术积分: 8584
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-17 13:52
个人简介

个人微薄: weibo.com/manuscola

文章分类

全部博文(146)

文章存档

2016年(3)

2015年(2)

2014年(5)

2013年(42)

2012年(31)

2011年(58)

2010年(5)

分类: 系统运维

2012-06-17 21:30:12

    RegExp对象常用的方法有test和exec。其中test在上一篇文章中已经露过面了,现在我们来分析这两个方法的区别和应用场景。

    exec是主要的方法,test的能力和江湖地位明显不如exec。因为pattern.test(text)只能返回true和false,即只能告诉我们是否找到匹配项,并不能返回找到的匹配项。如果仅需要知道是否存在匹配项,那么这种方法是非常方便,而且test方法一般是用在if语句中。

    对于exec方法而言,每次只会返回一个匹配项,无论是否设置标志位g。区别在于,设置了标志位g,下次执行exec那么返回下一个匹配项,而不设置标志位g,无论执行多少次exec,总是返回字符串的第一个匹配项。 

点击(此处)折叠或打开

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>RegExp exec() Example</title>
  5.     <script type="text/javascript">
  6.         var text = "friendly,quickly,fast,lovely,lying";
  7.         
  8.         var pattern = /.ly/g;
  9.         
  10.         var matches = pattern.exec(text);

  11.         alert(matches.index); //0
  12.         alert(matches[0]);
  13.         alert(pattern.lastIndex);

  14.         matches = pattern.exec(text);
  15.         alert(matches.index);
  16.         alert(matches[0]);
  17.         alert(pattern.lastIndex);
  18.         
  19.         matches = pattern.exec(text);
  20.         alert(matches.index);
  21.         alert(matches[0]);     
  22.         alert(pattern.lastIndex);

  23.     </script>
  24. </head>
  25. <body>

  26. </body>
  27. </html>


    如果去掉pattern中的标志位,结果是这样的:

点击(此处)折叠或打开

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>RegExp exec() Example</title>
  5.     <script type="text/javascript">
  6.         var text = "friendly,quickly,fast,lovely,lying";
  7.         
  8.         var pattern = /.ly/;
  9.         
  10.         var matches = pattern.exec(text);

  11.         alert(matches.index); //0
  12.         alert(matches[0]);
  13.         alert(pattern.lastIndex);

  14.         matches = pattern.exec(text);
  15.         alert(matches.index);
  16.         alert(matches[0]);
  17.         alert(pattern.lastIndex);
  18.         
  19.         matches = pattern.exec(text);
  20.         alert(matches.index);
  21.         alert(matches[0]);     
  22.         alert(pattern.lastIndex);

  23.     </script>
  24. </head>
  25. <body>

  26. </body>
  27. </html>

    这个lastIndex是RegExp实例的一个属性。表示搜索下一个匹配项的开始位置。除了这个属性外,RegExp还有global,ignoreCase, multiline,source属性。这些属性是顾名思义的。

参考文献:
1 Javascript高级程序设计 Nicholas C.Zakas著。
阅读(3154) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~