ES6正则对象(RegExp)

版权声明:本文为个人知识整理,欢迎指正、交流、转载。 https://blog.csdn.net/u014711094/article/details/79051707

0 RegExp的定义

let r = /is/gi;
let r = new RegExp('is', 'gi');
let r = new RegExp(/is/gi);         // 返回对象的copy
let r = new RegExp(/is/gi, 'i');    // r.flag='i',覆盖了原来的修饰符,这种方法在es5不允许

1 RegExp的方法

let str = 'this is a test.'
let r = /is/;

r.exec(str);    // ['is', index: 2, input: 'this is a test.'],返回匹配的结果,没有匹配返回null
r.test(str);    // true

// 重新编译,用于改变正则
r.compile(/t/g);    // =r.compile(/t/, 'g');

2 修饰符

2.1 g和i
let str = 'this IS a test.'
let r = /is/gi;

// lastIndex是下一次执行匹配的索引,RegExp带g修饰符的效果如下,只有i修饰符,lastIndex == 0
r.lastIndex;    // 0
r.exec(str);    // ['is', index: 2, input: 'this IS \na test.']
r.lastIndex;    // 4
r.exec(str);    // ['IS', index: 4, input: 'this IS \na test.']
r.lastIndex;    // 7
r.exec(str);    // null
r.lastIndex;    // 0

2.2 m

// 'm'支持多行(multiple)匹配,将'\n'认为是EOL
let str = 'this\ntest';

/this$/.test(str);     // false
/^test/.test(str);      // false

/this$/m.test(str);        // true
/^test/m.test(str);     // true
2.3 y
// 'y'要求lastIndex处必须匹配,开始lastIndex=0,默认开头必须匹配
let str = 'is is a test.';

//连续执行2次
/is/y.test(str);    // true
/is/y.test(str);    // false,lastIndex是空格' '
//连续执行2次
/is /y.test(str);   // true
/is /y.test(str);   // true
2.4 u
// todo:待测试

3 RegExp的属性

3.1 RegExp实例的属性
let r = /is/yuigm;

r.source;   // is
r.flags;    // gimuy,对象的修饰符

r.global;       // true
r.ignoreCase;   // true
r.multiple;     // true
r.unicode;      // true
r.sticky;       // true
3.2 RegExp的$1、$2、$3 …
let str = '1a,2b,3c,';
var r = /(\d)(\w)(,)/g;

r.exec(str);
r.exec(str);

RegExp.lastMatch;   // '2b,'返回最近一次的匹配
RegExp.$1;         // '2',对应第一个括号(\d)
RegExp.$2;         // 'b',对应第二个括号(\w)
RegExp.$3;         // ',',对应第三个括号(,)

str.replace(r, '$1$3$2_');   // 这里就可以随心所欲的替换了,在vscode/sublime中很有用

关于r.exec()的结果

let result = /is/.exec('this is a test.');  // ['is', index: 2, input: 'this is a test.']

// result是一个数组,根据编辑器的提示可以看到,数组的属性和方法result都有,多了index和input属性
result.length;  // 1,=result['length']
result.index;   // 2,=result['index']
result.input;   // 'this is a test.',=result['input']

// 相当于是这样
let arr = ['is'];
arr.index = 2;
arr.input = 'this is a test.';

猜你喜欢

转载自blog.csdn.net/u014711094/article/details/79051707