正则表达式(一)传送门
四. 捕获组
表达式 | 描述 |
---|---|
(x) | 捕获分组(缓存分组内容) |
- 作用:分组捕获的内容可以供表达式使用,或者最后输出
console.log('123'.match(/([0-9])([0-9])([0-9])/));
// [ '123', '1', '2', '3', index: 0, input: '123', groups: undefined ]
一个括号就是一个分组,最后输出了匹配的字符串以及3个分组的内容。
- 如何获取分组的内容?
- 在结果数组里获取
let res = '123'.match(/([0-9])([0-9])([0-9])/);
console.log(res[0]);// 123
console.log(res[1]);// 1
console.log(res[2]);// 2
console.log(res[3]);// 3
- RegExp.$n(n !== 0)
let res = '123'.match(/([0-9])([0-9])([0-9])/);
console.log(RegExp.$1);// 1
console.log(RegExp.$2);// 2
console.log(RegExp.$3);// 3
- 在表达式内反向引用(表达式内使用分组)
let res = 'aaa'.match(/([a-z])\1\1/);
console.log(res);
在表达式内部使用\number
获取捕获分组内容
五. 非捕获组与断言(非捕获组中的(?=y)
、(?!y)
、(?<=y)
、(?<!y)
被称为断言)
表达式 | 描述 |
---|---|
(?:x) | 匹配但不捕获 |
x(?=y) | 先行断言,即x在y的前面才匹配,不捕获 |
x(?!y) | 先行否定断言,即x不在y的前面才匹配,不捕获 |
(?<=y)x | 后行断言,即x必须以y开头才匹配,不捕获 |
(?<!y)x | 后行否定断言,即x开头不能为y,不捕获 |
网友评论