Chinaunix首页 | 论坛 | 博客
  • 博客访问: 351090
  • 博文数量: 213
  • 博客积分: 566
  • 博客等级: 中士
  • 技术积分: 1210
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-21 13:09
文章分类

全部博文(213)

文章存档

2015年(1)

2013年(7)

2012年(128)

2011年(77)

分类:

2012-06-18 15:12:46

    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著。
阅读(385) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~