正则匹配match和exec、search和test两组方法
2018-05-12 本文已影响0人
gaoshu883
正则匹配match
和exec
两个方法的对比表
方法名称 | 类 | 使用 |
---|---|---|
match | String | string.match(re) |
exec | RegExp | reg.exec(string) |
不同的使用情况▼
let re1 = /\d+/
let re2 = /(\d)+/
let re3 = /\d/g
let re4 = /(\d)+/g
let string = 'abccd123'
子表达式 | 全局匹配 | match | exec | 备注 |
---|---|---|---|---|
- | - | string.match(re1); // ["123"] |
re1.exec(string); // ["123"] |
match和exec结果一样都是返回数组 |
✓ | - | string.match(re2); // ["123","3"] |
re2.exec(string);//["123","3"] |
match和exec结果一样都是返回数组,均含子项 |
- | ✓ | 返回所有匹配项组成的数组string.match(re3);//["1","2","3"]
|
返回包含一个匹配项的数组,忽略全局匹配 re3.exec(string);//["1"]
|
|
✓ | ✓ | 返回所有匹配项组成的数组,忽略子表达式string.match(re4);//["1", "2", "3"]
|
返回包含一个匹配项的数组(含子项),忽略全局匹配re4.exec(string);//["1","1"]
|
注意:当全局匹配时,regexp实例的lastIndex属性实时改变,可以实现循环匹配,如下所示:
let content = '<img src="http://suo.im/4HtzkF"><img src="http://suo.im/4HtzoH">';
let pattern = /<img[^>]+src=['"]([^'"]+)['"]+/g;
let temp = null;
while ((temp = pattern.exec(content)) !== null) {
console.log(temp[1]);
}
正则匹配search
和test
两个方法的对比表
方法名称 | 类 | 使用 |
---|---|---|
search | String | string.search(re) |
test | RegExp | reg.test(string) |
不同的使用情况▼
全局匹配 | search | test |
---|---|---|
- | 返回 string 的第一个匹配位置,没有匹配时返回 -1 | 匹配 true,不匹配 false |
✓ | 同上 | lastIndex属性实时改变,可以实现循环匹配 |