let regex = new RegExp('xyz', 'i') // 等价于 let regex = /xyz/i let regex = new RegExp(/xyz/i) // 等价于 let regex = /xyz/i
注意!!!es6
let regex = new RegExp(/xyz/, 'i') // 这种写法是错误的
new RegExp(/abc/ig, 'i').flags // 第二个参数i会将前面的ig进行覆盖
let str="1 plus 2 equal 3" str.match(/\d+/g) // ['1','2','3']
let str = 'nihao Jack' str.replace(/Jack/, 'Lucy') // nihao Lucy
let str = 'good body' str.search(/body/) // 5 let str = 'good body' str.search(/girl/) // -1
let str = 'good body' str.split('o') ["g", "", "d b", "dy"]
let str = /hello/; let str2 = /hello/u; str.unicode // false str2.unicode // true
let str = 'aaa_aa_a' let reg1 = /a+/g let reg2 = /a+/y reg1.exec(s) // ['aaa'] reg2.exec(s) // ['aaa'] reg1.exec(s) // ['aa'] reg2.exec(s) // null y修饰符从剩余项的第一个位置开始(即_)因此找不到 lastIndex属性能够指定每次搜索的开始位置 reg2.lastsIndex = 1 reg2.exec(s) // ['aa'] 实际上y修饰符号隐含了头部匹配的标志^
'a1a2a3'.match(/a\d/y) // ['a1'] 'a1a2a3'.match(/a\d/gy) // ['a1','a2','a3']
const REG = /(\d{4})-(\d{2})-(\d{2})/ const matchObj = REG.exec('1999-12-31') const year = matchObj[1]; // 1999 const month = matchObj[2]; // 12 const day = matchObj[3]; // 31
问题: 只能用数字序号引用,组的顺序改变,引用的时候就必须修改序号正则表达式
const REG = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/ const matchObj = REG.exec('1999-12-31') const year = matchObj.groups.year // 1999 const month = matchObj.groups.month // 12 const day = matchObj.groups.day // 31 若是具名组没有匹配,那么对应的groups对象属性会是undefined
let {groups: {one, two}} = /^(?<one>.*):(?<two>.*)$/u.exec('foo:bar') console.log({one, two}) // {one: 'foo', two: 'bar'}