標籤:example post 表達 匹配 www. pat regex asc pattern
1.定義:檢測某個文本時,可以使用一種模式來描述要檢測的內容,RegExp就是這種模式。
2.文法:var patt=new RegExp(pattern,modifiers);或var patt=/pattern/modifiers;
模式描述了一個運算式模型,修飾符描述了檢索是否全域,區分大小寫。
3.RegExp修飾符,用於執行不區分大小寫匹配。
執行個體 1
在字串中不區分大小寫找"W3CSchool"
var str="Visit W3CSchool";
var patt1=/w3cschool/i;
以下標記的文本是獲得的匹配的運算式:
Visit W3CSchool
執行個體 2
全文尋找 "is"
var str="Is this all there is?";
var patt1=/is/g;
以下標記的文本是獲得的匹配的運算式:
Is this all there is?
執行個體 3
全文尋找和不區分大小寫搜尋 "is"
var str="Is this all there is?";
var patt1=/is/gi;
以下 標記的文本是獲得的匹配的運算式:
Is this all there is?
test()
test()方法搜尋字串指定的值,根據結果並返回真或假。
下面的樣本是從字串中搜尋字元 "e" :
執行個體
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
由於該字串中存在字母 "e",以上代碼的輸出將是:
true
當使用建構函式創造正則對象時,需要常規的字元轉義規則(在前面加反斜線 \)
執行個體
var re = new RegExp("\\w+");
exec()
exec() 方法檢索字串中的指定值。傳回值是被找到的值。如果沒有發現匹配,則返回 null。
下面的樣本是從字串中搜尋字元 "e" :
執行個體 1
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
由於該字串中存在字母 "e",以上代碼的輸出將是:
e
複製複製:https://www.2cto.com/kf/201601/487274.html
JavaScript RegExp 對象