正则表达式
声明一个正则表达式
字面量声明
const rex = /pattern/;
构造函数声明
const rex = new RegExp(pattern);
匹配模式
字符集合
let rex = /[bc]t/g;
let string = "actionbatbtctat";
console.log(string.match(rex)); // [ 'ct', 'bt', 'ct' ]
拓展
[a-z] 从小写a-z
[A-Z] 大写A-Z
[0-9] 0-9
[^a] 除了a以外的
符号范围:[#$%&@];
混合范围:[a-zA-Z0-9],匹配所有数字、大小写字母中的任意字符。
量词
let rex = /[a-z]{2}/g;
let string = "actionbbatbcctctat";
console.log(string.match(rex)); // [ 'ac', 'ti', 'on', 'bb', 'at', 'bc', 'ct', 'ct', 'at' ]
拓展
{3} 出现次数为最多3次
{1,4} 1 <= 出现次数 <= 4
{1,} 最少出现1次,简写 +
{0,} 至少0次,简写*
{0,1} 最少0次,最多1次,简写?
元字符
特殊字符
位置匹配
修饰符
实例方法
test() 和 exec()
const regex1 = /a/gi;
const regex2 = /hello/gi;
const str = "Action speak louder than words";
console.log(regex1.test(str)); // true
console.log(regex2.test(str)); // false
const regex1 = /a/gi;
const regex2 = /hello/gi;
const str = "Action speak louder than words";
console.log(regex1.exec(str)); // ['A', index: 0, input: 'Action speak louder than words', groups: undefined]
console.log(regex2.exec(str)); // null
字符串方法
search()
const regex1 = /a/gi;
const regex2 = /p/gi;
const regex3 = /m/gi;
const str = "Action speak louder than words";
console.log(str.search(regex1)); // 输出结果:0
console.log(str.search(regex2)); // 输出结果:8
console.log(str.search(regex3)); // 输出结果:-1
match()
const regex1 = /a/gi;
const regex2 = /a/i;
const regex3 = /m/gi;
const str = "Action speak louder than words";
console.log(str.match(regex1)); // 输出结果:['A', 'a', 'a']
console.log(str.match(regex2)); // 输出结果:['A', index: 0, input: 'Action speak louder than words', groups: undefined]
console.log(str.match(regex3)); // 输出结果:null
replace()
const regex = /a/g;
const str = "Action speak louder than words";
console.log(str.replace(regex, "A")); // 输出结果:Action speAk louder thAn words