1.正則表達式的創建
js創建正則表達式有兩種方式(我們一般會使用第一種):
1.通過類似Perl的語法:
let regexp1 = /pattern/flags
其中pattern是任何簡單或者復雜的表達式,可以包含字符類,限定符,分組,向前查找以及反向引用。
flag支持:g(全局匹配,找到第一個匹配項后還會繼續往后查找),i(不區分大小寫),m(多行模式,找完一行后還會找下一行)
例:
let pattern = /at/g;
2.通過使用RegExp構造函數
let regexp2 = new RegExp(string,flag)
RegExp構造函數支持兩個參數,參數都需要傳字符串
例:
let pattern = new RegExp("at","g");
二.關於pattern的使用
pattern中使用的方括號,元字符,量詞使用的方法見https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions
三.RegExp對象的方法
1.test()方法:檢索字符串中指定的值。返回 true 或 false
var pattern = /[hf]ello/g, str = 'hello'; pattern.test(str); //true pattern = /[ef]ello/g; pattern.test(str); //false
2.exec() 方法:用於檢索字符串中的正則表達式的匹配。返回一個數組,其中存放匹配的結果。如果未找到匹配,則返回值為 null。
var pattern = /[hf]ello/g, str = 'hello'; str = 'hello fello ello'; pattern.exec(str); //["hello", index: 0, input: "hello fello ello", groups: undefined] pattern.lastIndex //5 pattern.exec(str); //["fello", index: 6, input: "hello fello ello", groups: undefined] pattern.lastIndex //11 pattern.exec(str); //null pattern.lastIndex //0
注意:如果在一個字符串中完成了一次模式匹配之后要開始檢索新的字符串,就必須手動地把 lastIndex 屬性重置為 0。
var pattern = /[hf]ello/g, str = 'hello'; str = 'hello fello ello'; pattern.exec(str); //由於此時pattern.lastIndex=5,所以會從索引為5的地方開始匹配,因此下面這個會返回null pattern.exec('hello');//null
因此需要先設置pattern.lastIndex = 0;再將該模式應用到新的字符串。
3.compile()方法:用於改變和重新編譯正則表達式
function CompileDemo(){ var rs; var s = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPp" // Create regular expression for uppercase only. var r = new RegExp("[A-Z]", "g"); var a1 = s.match(r) // Find matches. // Compile the regular expression for lowercase only. r.compile("[a-z]", "g"); // Find matches. var a2 = s.match(r) return(a1 + "\n" + a2); }
備注:compile 方法將 pattern 轉換為內部的格式,從而執行得更快。例如,這允許在循環中更有效地使用正則表達式。當重復使用相同的表達式時,編譯過的正則表達式使執行加速。然而,如果正則表達式發生更改,則這種編譯毫無益處。
四.支持正則表達式的 String 對象的方法
1.search()方法:檢索與正則表達式相匹配的子字符串。返回匹配到的子字符串的起始位置。
var pattern = /[hf]ello/g, str = 'ss hello fello'; str.search(pattern);//3
2.match()方法:找到一個或多個正則表達式的匹配。返回存放匹配結果的數組(該數組的內容依賴於 regexp 是否具有全局標志 g,不管有沒有全局標志g),如果沒找到都返回null。
有全局標志g:
var pattern = /[hf]ello/g, str = 'ss hello fello'; str.match(pattern);// ["hello", "fello"]
無全局標志g(此時返回有點像regExp對象的exec方法):
var pattern = /[hf]ello/, str = 'ss hello fello'; str.match(pattern);//["hello", index: 3, input: "ss hello fello", groups: undefined]
3.replace(pattern,str)方法:替換一個與正則表達式匹配的子串。返回一個新的字符串(被模式匹配后的)
var pattern = /[hf]ello/g, str = 'ss hello fello'; str.replace(pattern,'world');//"ss world world"
4.split()方法:用參數中的字符串或者正則表達式來分割指定字符串。返回一個被字符串或者正則表達式分割過的數組。
var pattern = /[hf]ello/g, str = 'ss hello fello'; str.replace(pattern,'world');//["ss ", " ", ""]
五.綜合應用
1.姓名驗證
var pattern = /^[\u4E00-\u9FA5]{1,4}(.?)[\u4E00-\u9FA5]{1,4}$/, str = '好好是·哈哈'; pattern.test(str);//true
可支持”好好·好好“這種格式的姓名。
2.手機號校驗
var pattern = /^1[3,4,5,7,8,9][0-9]{9}$/, str = '13566666666'; pattern.test(str); //true
解釋一下,pattern中的表達式表示第一位以1開頭,第二位為3,4,5,67,8,9中的一個,后九位為0~9中的數字。具體量詞和方括號等的含義還是看這里 http://www.w3school.com.cn/jsref/jsref_obj_regexp.asp
開頭的^和結束的$是必須的,加^$的話就代表把整個要匹配的字符串當成一個整體做一次匹配,而不加則一個字符串可以匹配多次,只能代表這個字符串中有符合條件的並不代表改字符串符合條件。
3.身份證校驗
十八位身份證校驗:
// 前六位:[1-9]\d{5}
// 年份(1900-2099)(19|20)\d{2}
// 月日(例子上的是閏年,如果平年的話把后面的02(0[1-9]|[1-2][0-9])改成02(0[1-9]|1[0-9]|2[0-8])即可):( (01|03|05|07|08|10|12)(0[1-9]|[1,2][0-9]|3[0-1]) | (04|06|07|11)(0[1-9]|[1,2][0-9]|30) | 02(0[1-9]|[1-2][0-9]) )
// 三位順序碼:[0-9]{3}
// 校驗碼(0-9或者X或者x):[0-9Xx]
var pattern = /^[1-9]\d{5}(19|20)\d{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|07|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/;
var str = '23333319990223283X'; pattern.test(str); //true
十五位身份驗證思路跟這個類似,大家可以自己試一下。
4.標簽的匹配:
例:a標簽的匹配
var pattern = /<a\b[^>]+\bhref="([^"]*)"[^>]*>([\s\S]*?)<\/a>/ var str = '<a title="title" href="//www.baidu.com" class="hh"></a>'; pattern.test(str); //true
解釋一下,其中
<a\b 表示匹配a標簽的開始,
[^>]+ 匹配非>字符的一到多個任意字符
\bhref="([^"]*)" 匹配href的值,並且將匹配到的值捕獲到分組中
[^>]* 匹配href后除了>字符0到多個任意字符
([\s\S]*?) 匹配任意字符並捕獲到組中(包含空格和非空格字符,非貪婪匹配,也可以用.?但是.不能包含空行)
上面兩個分組的作用是方便匹配到相應的分組后獲取他,可用exec()方法獲取
pattern.exec(str); // ["<a title="title" href="//www.baidu.com" class="hh" ></a>", "//www.baidu.com", "", index: 0, input: "<a title="title" href="//www.baidu.com" class="hh" ></a>", groups: undefined]
匹配img標簽並且取出其中的title
function filterTagInContent(content){ var reg = /<img title="(.*?)" [^>]*>/; var matches = {}; //取出img標簽中的title來替換img標簽 while(matches = reg.exec(content)){ var imgTag = matches[0]; var title = matches[1] || '' content = content.replace(imgTag,title); } return content; } filterTagInContent('嘎嘎嘎嘎嘎嘎<img title="[好好]" src="111"/>哈哈哈哈'); //"嘎嘎嘎嘎嘎嘎[好好]哈哈哈哈"
應用實例先說這么多,到后面用到再添加。