ECMAScript(正则)

2019-06-05  本文已影响0人  fangPeng__

RegExp 构造函数

// 原有正则对象的修饰符是ig,它会被第二个参数i覆盖
new RegExp(/abc/ig, 'i')
// es5这样写会报错    es5写法   new RegExp('abc', 'i')

u 修饰符

// 正确处理大于\uFFFF的 Unicode 字符

console.log(/^\uD83D/u.test('\uD83D\uDC2A')) // false
console.log(/^\uD83D/.test('\uD83D\uDC2A')) // true
var s = '𠮷';
/^.$/.test(s) // false
/^.$/u.test(s) // true
/\u{61}/.test('a') // false
/\u{61}/u.test('a') // true
/\u{20BB7}/u.test('𠮷') // true
/a{2}/.test('aa') // true
/a{2}/u.test('aa') // true
/𠮷{2}/.test('𠮷𠮷') // false
/𠮷{2}/u.test('𠮷𠮷') // true

y 修饰符

y修饰符相当于在匹配正则里加入^,强制以匹配字符开头

const regEx1 = /a+/gy
const regEx2 = /a+/g
'abaabaaa'.match(regEx2) // [ 'a', 'aa', 'aaa' ]
'abaabaaa'.match(regEx1) // [ 'a' ]

s 修饰符

点匹配符可以匹配除了/r或者/n 之外的所有字符(四个字节的 UTF-16可以用u修饰匹配到)如果想让点匹配符匹配/r/n 可以加s修饰符

/foo.bar/.test('foo\nbar')
// false
/foo.bar/s.test('foo\nbar') // true

新增属性

const r1 = /hello/;
const r2 = /hello/u;

r1.unicode // false
r2.unicode // true
// ES5 的 source 属性
// 返回正则表达式的正文
/abc/ig.source
// "abc"

// ES6 的 flags 属性
// 返回正则表达式的修饰符
/abc/ig.flags
// 'gi'

断言

/\d+(?=%)/g.match('100%lalala12121')  // ["100"]
/\d+(?!%)/g.match('100%lalala12121')     // ["12121"]
/(?<=\$)\d+/.match('$100ffffff200')  // ["100"]
/(?<!\$)\d+/g.match('$100ffffff200')  // ["200"]

具名组匹配

const RE_DATE = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;

const matchObj = RE_DATE.exec('1999-12-31');
const year = matchObj.groups.year; // 1999
const month = matchObj.groups.month; // 12
const day = matchObj.groups.day; // 31
let {groups: {one, two}} = /^(?<one>.*):(?<two>.*)$/u.exec('foo:bar');
one  // foo
two  // bar


let re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;
'2015-01-02'.replace(re, '$<day>/$<month>/$<year>')
// '02/01/2015'


replace方法的第二个参数也可以是函数
'2015-01-02'.replace(re, (
   matched, // 整个匹配结果 2015-01-02
   capture1, // 第一个组匹配 2015
   capture2, // 第二个组匹配 01
   capture3, // 第三个组匹配 02
   position, // 匹配开始的位置 0
   S, // 原字符串 2015-01-02
   groups // 具名组构成的一个对象 {year, month, day}
 ) => {
 let {day, month, year} = groups;
 return `${day}/${month}/${year}`;
});

const RE_TWICE = /^(?<word>[a-z]+)!\k<word>$/;
RE_TWICE.test('abc!abc') // true
RE_TWICE.test('abc!ab') // false

数字引用(\1)依然有效。

const RE_TWICE = /^(?<word>[a-z]+)!\1$/;
RE_TWICE.test('abc!abc') // true
RE_TWICE.test('abc!ab') // false



const RE_TWICE = /^(?<word>[a-z]+)!\k<word>!\1$/;
RE_TWICE.test('abc!abc!abc') // true
RE_TWICE.test('abc!abc!ab') // false
上一篇 下一篇

猜你喜欢

热点阅读