JavaScript引用類型——「RegExp類型」的注意要點

EegExp 類型

ECMAScript 經過RegExp 類型來支持正則表達式。語法以下:html

var expression = / pattern / flags;

每一個正則表達式均可帶有一或多個標誌(flags),正則表達式的匹配模式支持下列3 個標誌。正則表達式

  • g:表示全局(global)模式,該模式將被應用於全部字符串,而非在發現第一個匹配項時當即中止;express

  • i:表示不區分大小寫(case-insensitive)模式,該模式在肯定匹配項時忽略模式與字符串的大小寫;數組

  • m:表示多行(multiline)模式,在到達一行文本末尾時還會繼續查找下一行中是否存在與模式匹配的項;函數

    如:測試

    var pattern1 = /at/g; //匹配字符串中全部「at」的實例
    var pattern2 = /[bc]at/i; //匹配字符串第一個「bat」或「cat」,不區分大小寫
    var pattern3 = /.at/gi; //匹配字符串中全部以「at」結尾的3個字符串的組合,不區分大小寫this

    與其餘語言中的正則表達式相似,模式中使用的全部元字符都必須轉義。正則表達式中的元字符包括:設計

( [ { \ ^ $ | ? * + . ] )

如:code

var pattern1 = /\[bc\]at/i; //匹配第一個「[bc]at」,不區分大小寫;
var pattern2 = /\.at/gi; //匹配全部「.at」,不區分大小寫;

另外,還可使用RegExp 構造函數,它接收兩個參數:一個是要匹配的字符串模式,另外一個是可選的標誌字符串。如:htm

var pattern1 = new RegExp("[bc]at","i");

因爲RegExp 構造函數的模式參數是字符串,因此在某些狀況下要對字符串進行雙重轉義。全部元字符串都必須雙重轉義,如\n 一般被轉義爲\\n,而在正則表達式中就會變成\\\n。如:

/\[bc\]at/             => \\[bc\\]at
/\.at/                   => \\.at
/name\/age/            => name\\/age
/\d.\d{1,2}/        => \\d.\\d{1,2}
/\w\\hello\\123/    => \\w\\\\hello\\\\123

正則表達式字面兩始終會共享同一個RegExp 實例,而使用構造函數建立的每個新RegExp 實例都是一個新實例。如:

var re = null,i;

for (var i = 0; i < 10; i ++){
    re = /cat/g;
    re.test("catastrophe");
}

for (var i = 0; i < 10; i ++){
    re = new RegExp("cat","g");
    re.test("catastrophe");
}

對於第一個,因爲會測試到字符串末尾,因此下次再調用test()就要從頭開始。而第二個循環使用RegExp 構造函數在每次循環衝建立正則表達式。由於媒體迭代都會建立一個新的RegExp 實例,因此每次調用text()都會返回true。

RegExp 實例屬性

  • global:布爾值,是否設置了g;

  • ignoreCase:布爾值,是否設置了i;

  • multiline:布爾值,是否設置了m;

  • lastIndex:整數,開始搜索下一個匹配項的字符位置,從0 開始算起;

  • source:正則表達式的字符串表示,按照字面量形式返回

如:

var pattern = new RegExp("\\[bc\\]at","i");
document.write(pattern.global); //false
document.write(pattern.ignoreCase); //true
document.write(pattern.multiline); //false
document.write(pattern.lastIndex); //0
document.write(pattern.source); //\[bc\]at

注意最後一個,source 屬性保存的是規範形式的字符串,就是字面量形式所用的字符串。

RegExp 實例方法

主要有兩個方法,一個是exec()方法,一個是test()方法。

exec()方法是專門爲捕獲組而設計的。接收一個字符串參數,而後返回包含第一個匹配項信息的數組;或者null;返回的數組還額外包含兩個屬性:index 和input。在數組中,第一項是與整個模式匹配的字符串,其餘項是與模式中的不活組匹配的字符串。如:

var text = "mom and dad and baby";
var pattern = /mom( and dad( and baby)?)?/gi;

var matches = pattern.exec(text);
console.log(matches.index);
console.log(matches.input);
console.log(matches[0]);
console.log(matches[1]);
console.log(matches[2]);

/*
[Log] 0 (repetition.html, line 33)
[Log] mom and dad and baby (repetition.html, line 34)
[Log] mom and dad and baby (repetition.html, line 35)
[Log]  and dad and baby (repetition.html, line 36)
[Log]  and baby (repetition.html, line 37)
*/

由於整個字符串自己與模式匹配,因此返回的數組matches 的index 爲0;數組中的第一項是匹配的整個字符串,第二項包含與第一個不活租匹配的內容,第三項包含與第二個捕獲組匹配的內容。

第一個例子,這是一個全局模式:

var text = "this is a Global setting not a global function";
var pattern = /global/gi;

var matches = pattern.exec(text);
console.log(matches); //["Global"]
console.log(matches.index); //10
console.log(matches.input); //this is a Global setting not a global function
console.log(matches[1]); //undefined 這裏沒有捕獲組
console.log(matches[0]); //Global
console.log(pattern.lastIndex); //16

matches = pattern.exec(text);
console.log(matches); //["global"]再次調用該exec()則繼續查找新的匹配項
console.log(matches.index); //31
console.log(pattern.lastIndex); //37

第二個例子,這不是一個全局模式:

var text = "this is a Global setting not a global function";
var pattern = /global/i;

var matches = pattern.exec(text);
console.log(matches); //["Global"]
console.log(matches.index); //10
console.log(pattern.lastIndex); //0

matches = pattern.exec(text);
console.log(matches); //["Global"] 這裏仍然是Global,說明非全局模式會從頭開始搜索。
console.log(matches.index); //10
console.log(pattern.lastIndex); //0

全局模式,每次調用exec()都會返回字符串中的下一個匹配項;而非全局模式,每次調用exec()返回的都是第一個匹配項。

test()方法則是接收一個字符串參數。在模式與該參數匹配的狀況下返回true;不然返回false。一般在只想知道目標字符串與某個模式是否匹配,但不須要知道文本內容的狀況下,使用這個方法很是方便。

var text = "testing!";
var pattern = /est/gi;

if (pattern.test(text)){
    document.write("matched")
}else{
    document.write("not matched")
}

RegExp 構造函數屬性

這些屬性有一個長屬性名也有一個短屬性名。最經常使用的有兩個:

  1. leftContext($` input 字符串中lastMatch 以前的文本);

  2. rightContext ($' input 字符串中lastMatch 以後的文本);

其餘幾個屬性Opera 和IE 對此兼容很差。有:

  1. input ($_ 最近一次要匹配的字符串);

  2. lastMatch ($& 最近的一次匹配項);

  3. lastParen ($+ 最近一次的捕獲組);

  4. multiline ($* 返回布爾值,表示是否全部表達式都使用多行模式);

如:

var text = "hello there";
var pattern = / /gi;
if(pattern.exec(text)){
    document.write("targeted" + "<br/>");
    document.write(RegExp.leftContext);
    document.write(RegExp.rightContext);
}else{
    document.write("missed" + "<br/>");
}

又如:

var text = "hello there";
var pattern = / /gi;
if(pattern.exec(text)){
    document.write("targeted" + "<br/>");
    document.write(RegExp.input); //hello there
    document.write(RegExp.multiline); //false
}else{
    document.write("missed" + "<br/>");
}

由於短屬性名不是有效的標識符,所以必須經過方括號語法來訪問它們。如RegExp["$'"]

另外,還有9 個用於存儲捕獲組的構造函數屬性。語法是RegExp.$1`RegExp.$2`等等。如:

var text = "this has been a short summer";
var pattern = /(..)or(.)/g;

if (pattern.test(text)){
    document.write(RegExp.$1);
    document.write(RegExp.$2);
}

模式的缺陷

具體訪問模式的侷限

相關文章
相關標籤/搜索