正則表達式
概念
本節講正則表達式在js中的使用,注意正則對象是一個引用類型。
初始化:字面量和對象使用
與對象的定義一樣,我們可以使用字面量定義正則表達式,也可以使用正則對象來定義正則表達式,他們的區別是使用的轉義有一定差別。
在使用字面量的時候,使用/ /把正則表達式包起來,後面可以寫上匹配模式或者不寫,不寫默認不是全局匹配,我們在使用的時候,一般都是使用字面量來初始化,因爲這樣比較簡單,轉義也不像字符串那麼複雜。
// 正則表達式 /at/g 表示匹配所有at /g表示全局搜索
var pattern1 = /at/g; // 注意不用字符串
var pattern2 = RegExp('/at', 'g');
下面這些需要轉義:
正則對象的屬性
由於正則對象的屬性都可以在字面變量中看得到,所以這些方法用處並不大,知道就好:
exec() 方法(捕獲方法)
exec方法執行的結果不是所有匹配的項,而是第一個匹配到的項,他的返回值如下面的代碼顯示(關於捕獲組的概念,我們以後用到了再講,這裏我們知道每次只會匹配一個,在數組的第0個位置返回)
// exec的返回值
var text = 'mom and dad and baby';
var pattern = /mom( and dad( and baby)?)?/gi;
var matches = pattern.exec(text);
alert(matches.index); // 0 // 擁有index屬性標識匹配項再字符串中的位置
alert(matches.input); // mom and dad and baby // 標識原字符串
alert(matches[0]); //mom and dad // 標識匹配的字符串
alert(matches[1]); //and dad //捕獲組匹配的字符串
alert(matches[2]); //and baby
exec方法要注意全局標誌 /g 對於執行結果的影響,不寫/g的時候,不是全局匹配,每一次執行都是從頭開始,寫了/g,匹配是全局的,下一次匹配是從上一次的基礎之上繼續往後匹配,看下面的例子就可以說明這個情況
// 不寫/g 每一次都是從頭開始匹配
var text = 'cat, bat, sat, fat';
var pattern1 = /.at/;
var matches = pattern1.exec(text);
alert(matches.index); //0
alert(matches[0]); //cat
alert(pattern1.lastIndex); //0 //lastIndex方法是問題的關鍵,注意它是pattern1對象的屬性,其實就記錄了這個正則匹配到哪個位置了,這裏都是0說明是一直從零開始匹配
matches = pattern1.exec(text);
alert(matches.index); //0
alert(matches[0]); //cat
alert(pattern1.lastIndex); //0
加上/g我們再看看結果有什麼變化
var text = 'cat, bat, sat, fat';
var pattern1 = /.at/g;
var matches = pattern1.exec(text);
alert(matches.index); //0
alert(matches[0]); //cat
alert(pattern1.lastIndex); //3 //lastIndex標識經過了這次匹配,下次匹配應該從什麼位置開始進行
matches = pattern1.exec(text);
alert(matches.index); //5 // 標識匹配到的位置
alert(matches[0]); //bat
alert(pattern1.lastIndex); //8
test方法
test方法用於匹配之後返回true false,如果只想知道有無匹配,不想知道具體結果,就用這個。常用於if語句中,判斷用戶輸入是否有效等。
var text = '000-00-0000';
var pattern = /\d{3}-\d{2}-\d{4}/;
if (pattern.test(text)) {
alert('matched'); //matched
}
全局屬性
通過RegExp的屬性,我們可以獲知一些全局的正則信息,比如剛剛匹配輸入了什麼字符串,上次匹配了哪些信息,這個有點像全局的靜態變量,我們看看全局屬性支持哪些信息的獲取
注意使用長屬性名和短屬性名都可以獲取全局屬性。我們下面看看長短屬性的使用