1. 程式人生 > >ES6正則物件(RegExp)

ES6正則物件(RegExp)

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.';