正则表达式是用于匹配字符串中字符组合的模式。正则表达式
两种方式: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})$/