一、正则表达式:字符串的校验(验证) --- 字符串
正则的创建
字面量创建 /匹配的字符串/
实例化对象 new RegExp('匹配的字符串')
二、正则的修饰符
i ignore 忽略大小写
var reg1 = /tmd/i
g global 全局的
const reg2 = /tmd/g
三、正则的方法
text() 返回布尔值
exec() 返回的是一个数组 --- 总是匹配一个,如果匹配不到就返回null
补充知识点
[ ] -> true
const reg = /tmd/ig
const str = 'hello tmd Tmd'
// test正则的方法 测试字符串中是否有匹配正则的内容 -- 布尔值 一般次正则不需要全局匹配
console.log(reg.test(str)); // true /
// 返回的是一个数组 --- 总是匹配一个,如果匹配不到就返回null
console.log(reg.exec(str));
// ['Tmd', index: 10, input: 'hello tmd Tmd', groups: undefined]
四、正则的内容
五、转义字符
转义使用 \
// 匹配 \/
const reg = /\ \//
console.log(reg.test(' \/'));
// 匹配 .
const reg2 = /\./
// 匹配[
const reg3 = /\[/
console.log(reg3.test('[]]')); // true
console.log(reg2.test('hq')); // false
// + ? * {} 匹配的次数,需要前面有匹配的东西
// const reg4 = /+/
// 报错 /+/: Nothing to repeat
const reg4 = /\+/
console.log(reg4.test('+')); // true
六、简写
七、中文
const reg = /^[\u4e00-\u9fa5]{3,6}$/
console.log(reg.test('你好啊')); // true
八、字符串使用到正则的方法
// 替换敏感词
function replaceMinGan(str,arr,n){
n = n || '**';
// const mgc = ['tmd','md','wc'];
const word = arr.join('|');
const reg = new RegExp(word,'ig')
return str.replace(reg,n)
}
const mgc = ['tmd','md','wc']
const res = replaceMinGan('wc,正则真tmd简单啊,Wc',mgc)
console.log(res); // **,正则真**简单啊,**
const str2 = 'good day day up'
console.log(str2.search('day'));
// 5 search = indexOf
console.log(str2.search(/da*y/gi));
// 5 search 可以使用正则,但是indexOf不能使用正则
console.log(str2.match(/da*y/gi)); // 找到满足条件的字符 ['day', 'day']
const str3 = 'good good study day day up'
// 贪婪匹配
console.log(str3.split(/ +/));
// ['good', 'good', 'study', 'day', 'day', 'up']
九、常见的正则练习
const reg = /^[\w,\+]+@\w+\.(com|cn|com\.cn)$/
console.log(reg.test('1,+23@q.com.cn'));
// true
// 身份证号 18位 17位数字+数字或者X
const reg2 = /^\d{17}[\dX]$/
console.log(reg2.test('22222219990929191X'));
// true
// 身份证 6位 4位出生年份 2月份 2日期 3数字 ,数字或者X
const reg3=/^\d{6}(19|20)\d{2}(0|1)\d(0|1|2|3)\d{4}[\dX]$/
console.log(reg3.test('22222219991929191X'));
// true
// 删除所有的空格
const str = ' good good study day day up '
// const arr = ['',' ',' '] ...
// 替换
console.log(str.replace(/ +/g,''));
// goodgoodstudydaydayup 替换成空 就相当于把它删了
console.log(str);
console.log(str.replace(/^ +| +$/g,''));
// good good study day day up
console.log(str.replace(/ +/g,' '));
// good good study day day up