MDN 正则表达式
1. 创建正则表达式对象:
使用构造函数:
const regex = new RegExp('pattern', 'flags');
使用字面量:
const regexLiteral = /pattern/flags;
标志
g:全局搜索
i:不区分大小写搜索
m:多行搜索
s:允许 . 匹配换行符
u:使用 unicode 码的模式进行匹配
y:执行 “粘性” 搜索,匹配从目标字符串的当前位置开始
2. 基本匹配:
字符匹配:
const regex = /hello/;
const result = regex.test('hello world');
console.log(result);
字符集:
const regex = /[aeiou]/;
const result = regex.test('hello');
console.log(result);
3. 修饰符:
i - 不区分大小写:
const regex = /hello/i;
const result = regex.test('Hello World');
console.log(result);
g - 全局匹配:
const regex = /hello/g;
const result = 'hello world'.match(regex);
console.log(result);
4. 元字符:
. - 任意字符:
const regex = /h.llo/;
const result = regex.test('hello');
console.log(result);
^ - 开头匹配:
const regex = /^hello/;
const result = regex.test('hello world');
console.log(result);
$ - 结尾匹配:
const regex = /world$/;
const result = regex.test('hello world');
console.log(result);
5. 量词:
* - 零次或多次匹配:
const regex = /go*d/;
const result = regex.test('good');
console.log(result);
+ - 一次或多次匹配:
const regex = /go+d/;
const result = regex.test('good');
console.log(result);
? - 零次或一次匹配:
const regex = /go?d/;
const result = regex.test('god');
console.log(result);
6. 分组和捕获:
分组 ( ):
const regex = /(\d+)-(\w+)/;
const result = '123-abc'.match(regex);
console.log(result);
7. 特殊字符的转义:
const regex = /a\*b/;
const result = regex.test('a*b');
console.log(result);
8. 其他常用方法:
test() - 测试字符串是否匹配正则表达式:
const regex = /hello/;
const result = regex.test('hello world');
console.log(result);
exec() - 查找匹配项,并返回数组:
const regex = /\d+/;
const result = regex.exec('abc 123 xyz');
console.log(result);
match() - 在字符串中查找匹配项,并返回数组:
const regex = /\d+/;
const result = 'abc 123 xyz'.match(regex);
console.log(result);