1. 程式人生 > >JavaScript 正則表達式(RegExp)

JavaScript 正則表達式(RegExp)

指定 表達 正則表達式 false logs () res exec target

什麽是RegExp

RegExp是一種模式用來描述要檢索的內容。

定義RegExp

1 var patt = new RegExp("模式");

RegExp對象的方法

RegExp對象有3個方法:test()、exec()、compile()

test()

檢索字符串中指定的值。返回值為true或者false

1 var patt = new RegExp("e");
2 document.write(patt.test("I am a student");
3 //返回值
4 true

exec()

檢索字符串中指定的值。返回值為找到的值,如果沒有發現匹配,返回null。

1 var
patt = new RegExp("e"); 2 document.write(patt.exec("I am a student.); 3 //返回值 4 e

可以設定第二個參數來設定檢索

g:全局檢索

i:執行對大小寫不敏感的匹配

m:執行多行匹配

1 var patt = new RegExp("e", "g");
2 do {
3     result = patt.exec("I am a student in the university");
4     document.write(result);
5 } while (result != null);
6 //執行結果
7 eeenull

compile()

用於改變RegExp。

即可以改變檢索模式,也可以添加或刪除第二個參數。

1 var patt = new RegExp("e");
2 document.write(patt.test("I am a student");
3 patt.compile("b");
4 document.write(patt.test("I am a student");
5 //輸出結果
6 truefalse

 總結自:http://www.w3school.com.cn/js/js_obj_regexp.asp

JavaScript 正則表達式(RegExp)