正則表達式是用於匹配字符串中字符組合的模式。正則表達式
兩種方式:chrome
1.new RegExp()數組
let pattern1 = new RegExp('cat'); //第一個參數字符串 let pattern2 = new RegEXP('cat', 'ig'); //第二個參數可選模式修飾符
2.字面量(如下栗子均使用字面量的方式建立正則表達式)測試
let pattern3 = /cat/; let pattern4 = /cat/ig;
1.test
在字符串中測試是否匹配的RegExp方法,它返回true或false。google
let str = 'This is a cat!'; console.log(pattern4.test(str)); //true
2.exec
在字符串中執行查找匹配的RegExp方法,它返回一個數組(未匹配到則返回null)。編碼
console.log(pattern4.exec(str)); //[cat]
3.match
在字符串中執行查找匹配的String方法,它返回一個數組或者在未匹配到時返回null。firefox
console.log(str.match(pattern4)); //[cat]
4.replace
在字符串中執行查找匹配的String方法,而且使用替換字符串替換掉匹配到的子字符串。code
console.log(str.replace(pattern4, 'dog')); //This is a dog!
5.search
在字符串中測試匹配的String方法,它返回匹配到的位置索引,或者在失敗時返回-1。索引
console.log(str.search(pattern4)); //10
6.split
使用正則表達式或者一個固定字符串分隔一個字符串,並將分隔後的子字符串存儲到數組中的String方法。字符串
console.log(str.split(pattern4)); //["This is a ", "!"]
重複匹配(?、*、+、.、{m,n})
let str = 'google', str1 = 'gooooogle', str2 = 'ggle', pattern = /g..gle/, pattern1 = /go*gle/, pattern2 = /go+gle/, pattern3 = /g.*gle/,//0個或多個的任意字符 pattern4 = /go?gle/, pattern5 = /go{2,4}gle/, pattern6 = /go{3}gle/,//匹配3個o->gooogle pattern7 = /go{3,}gle/;//匹配3個或3個以上o console.log(pattern.test(str));//true console.log(pattern1.test(str));//true console.log(pattern1.test(str1));//true console.log(pattern2.test(str1));//true console.log(pattern2.test(str2));//false console.log(pattern3.test(str));//true console.log(pattern3.test(str2));//true console.log(pattern4.test(str));//false console.log(pattern7.test(str1));//true
字符類匹配
空白字符
貪婪模式和非貪婪模式
?緊跟在任何量詞 *、 +、? 或 {} 的後面,將會使量詞變爲非貪婪的(匹配儘可能少的字符),和缺省使用的貪婪模式(匹配儘量多的字符)正好相反。
console.log('123abc'.match(/\d+/)); //[123] console.log('123abc'.match(/\d+?/)); //[1]
捕獲和非捕獲
(x)匹配 'x' 而且記住匹配項。括號被稱爲 捕獲括號。
console.log(/(\d+)([a-z]+)/.exec('123abc')); //[12abc, 123, abc] console.log(/(\d+)(?:[a-z]+)/.exec('123abc')); //[123abc, 123]
正向確定查找和正向否認查找
x(?=y)匹配'x'僅僅當'x'後面跟着'y'.這種叫作正向確定查找。
x(?!y)匹配'x'僅僅當'x'後面不跟着'y',這個叫作正向否認查找。
console.log(/goo(?=gle)/.exec('google')); //[goo] console.log(/goo(?=gle)/.exec('goodu')); //null console.log(/goo(?!gle)/.exec('google')); //null console.log(/goo(?!gle)/.exec('goodu')); //[goo]
1.手機號(1xxxxxxxxxx):/^1[0-9]{10}$/2.郵政編碼校驗:/[1-9][0-9]{5}/3.匹配漢字:[u4e00-u9fa5]4.簡易郵箱校驗:/^([a-zA-Z0-9_\.\-]+)@([a-zA-Z0-9_\.\-]+)\.([a-zA-Z]{2,4})$/