js正則標誌/g /i /m的用法,以及例項

一任天然發表於2012-03-21

——轉自http://hi.baidu.com/zhnwi/blog/item/a72df13ba244553d96ddd807.html

js正則標誌/g /i /m的用法,以及例項

正則的思想都是一樣的,但是具體的寫法會有所不同,在這裡提到的/g,/i,/m在其他的地方也許就不能用了。

一,js正則標誌/g,/i,/m說明

1,/g 表示該表示式將用來在輸入字串中查詢所有可能的匹配,返回的結果可以是多個。如果不加/g最多隻會匹配一個

2,/i  表示匹配的時候不區分大小寫

3,/m 表示多行匹配,什麼是多行匹配呢?就是匹配換行符兩端的潛在匹配。影響正則中的^$符號


二,例項說明

1,/g的用法

  1. <script type="text/javascript">  
  2. str = "tankZHang (231144)"+  
  3.  "tank ying (155445)";  
  4. res = str.match(/tank/);    //沒有加/g  
  5. alert(res);                 //顯示一個tank  
  6.   
  7. res = str.match(/tank/g);   //加了/g  
  8. alert(res);                 //顯示為tank,tank  
  9. <strong></script></strong>  

2,/i的用法

  1. <script type="text/javascript">  
  2. str = "tankZHang (231144)"+  
  3.  "tank ying (155445)";  
  4. res = str.match(/zhang/);      
  5. alert(res);                  //顯示為null  
  6.   
  7. res = str.match(/zhang/i);   //加了/i  
  8. alert(res);                  //顯示為ZHang  
  9. </script>  

3,/m的用法

  1. <script type="text/javascript">  
  2. var p = /$/mg;  
  3. var s = '1\n2\n3\n4\n5\n6';  
  4. alert(p.test(s));  //顯示為true  
  5. alert(RegExp.rightContext.replace(/\x0A/g, '\\a'));  //顯示\a2\a3\a4\a5\a6  
  6. alert(RegExp.leftContext);    //顯示為豎的2345  
  7. alert(RegExp.rightContext);   //顯示為6  
  8.   
  9. var p = /$/g;  
  10. var s = '1\n2\n3\n4\n5\n6';  
  11. alert(p.test(s));  //顯示為true  
  12. alert(RegExp.rightContext.replace(/\x0A/g, '\\a'));  //什麼都不顯示  
  13. alert(RegExp.leftContext);    //顯示為豎的123456  
  14. alert(RegExp.rightContext);   //什麼都不顯示  
  15.   
  16. var p = /^/mg;  
  17. var s = '1\n2\n3\n4\n5\n6';  
  18. alert(p.test(s));    //顯示為true  
  19. alert(RegExp.rightContext.replace(/\x0A/g, '\\a')); //顯示為1\a2\a3\a4\a5\a6  
  20. alert(RegExp.leftContext);     //顯示為豎的12345  
  21. alert(RegExp.rightContext);    //顯示為6  
  22. </script>   
  23.   
  24. //從上例中可以看出/m影響的^$的分割方式  

上面說的三個例子,/i,/g,/m分開來說的,可以排列組合使用的。個人覺得/m沒有多大用處

相關文章