javaScript正則表達式

  1、web

      什麼是正則表達式:官方的解釋是:正則是匹配字符串特定模式的一種表達式。換句話就是正則表達式就是用來匹配字符串的。正則表達式

2、建立正則表達式的方式:數組

    一、方式一:app

var box = new RegExp("no pain no gain","igm");

在方式一中的參數而是能夠省略的。其中,i表示忽略大小寫,默認是區分大小寫的。g是表明全局匹配(後面詳細說明),m表示多行匹配.三個參數能夠單獨使用也能夠一塊兒使用函數

    二、方式二:測試

var box =/you are the best/igm;

3、測試正則表達式的函數:google

   一、RegExp包含兩個函數test()和exec()。test()返回true或false,而exec()返回匹配到的數組spa

    1.一、test()code

  var pattern = new RegExp("This is box","ig");//建立正則表達式忽略大小寫,全局匹配
    var str = "box";
   alert( pattern.test(str));//返回true

   1.二、exec()orm

  var pattern = /This is box/ig;//建立正則表達式忽略大小寫,全局匹配
   var str = "box";
  var a = pattern.exec(str);//返回數組

   alert(a[0]);//打印出box

二、除lRegExp提供了test()和exec()兩種測試正則表達式的方法String也提供了測試正則表達式的方法,match(pattern),replace(pattern,repalcement),search(pattern),split(pattern)

2.一、match(pattern)返回pattern中的子串或則null

var pattern = /This is a box,This is a cat/ig
var str = "This";
var a = str.match(pattern);
alert(a.length);//打印出2
alter(a[0]);//打印出This

若是將上面的的例子改爲一下形式(把g去掉)

 

var pattern = /This is a box,This is a cat/i
var str = "This";
var a = str.match(pattern);
alert(a.length);//打印出1
alter(a[0]);//打印出This

 

var pattern = /This is a box,This is a cat/
var str = "This";
var a = str.match(pattern);
alert(a.length);//打印出0
alter(a[0]);//打印出undefind

2.二、replace(pattern,str1);用str1替換

var pattern = /This is a box,This is a cat/i
var str = "This";
str.replacee(pattern,"That");
alter(pattern );//輸出That is a box,This is a cat

var pattern = /This is a box,This is a cat/ig
var str = "a";
var a = str.search(pattern);

alert(a);//返回8

2.四、split(pattern)//返回分割後的數組

var pattern = /a/ig
var str = "This is a box,This is a cat";
var a = str.split(pattern);
alert(a.length);//打印出3

 

 4、獲取控制

一、

1.一、[a-z0-9]匹配括號中字符的任意一個

1.二、. 匹配任意一個字符

1.三、[^a-z0-9]匹配不在括號中的字符的任意一個

1.四、\d匹配數字[0-9]

1.五、\D匹配非數字[^0-9]

1.六、\w匹配數字,字母及下劃線

1.七、\W匹配非數字字母及下劃線

1.八、\0匹配null,\b匹配空格字符,\n匹配換行,\r匹配回車,\s匹配空白字符,空格,製表符,換行符 \S匹配非空白字符

1.九、^行首匹配,$行尾匹配,

1.十、x?匹配x0次或1次,x*匹配x任意次,x+匹配x1次或屢次,(xyz)+匹配xyz一次或屢次,x{n,m}匹配xn到m次

1.十一、|herro|where|why匹配herro,where,why中的任意一個

1.十二、\1或者$1匹配第一個分組的內容   ,   \2或者$2匹配第二個分組的內容       ,\3或者$3匹配第三個分組的內容  

二、

2.一、前瞻性捕獲

var pattern = (goo(?=gle));//goo後面必須跟着gle才捕獲
var str= google;
alert(pattern.exec(str));

2.二、捕獲性分組:指的是RegExp.$1這個屬性的值

 var str = "This is box ,This is apple";
 var reg = /(This ){1}(p){2}/gi;
 reg.test(str); // 要必須匹配以後纔有下面的值
 alert(RegExp.$1); //output "This"
 alert(RegExp.$2); //output "pp"

非捕獲分組模式:上面說了捕獲分組,那非捕獲分組其實就是不讓RegExp.$1引用了

 var str = "#123456789";
 var reg = /#(?:\d+)/;
 reg.test(str);
 alert(RegExp.$1);      //output "" 注意這裏取消了反向引用就爲空了
相關文章
相關標籤/搜索