正则的扩展
发布时间:2020-12-14 06:10:37 所属栏目:百科 来源:网络整理
导读:1.RegExp构造函数 ES5中有两种情况 let regex = new RegExp('xyz','i')// 等价于let regex = /xyz/ilet regex = new RegExp(/xyz/i)// 等价于let regex = /xyz/i 注意!!! let regex = new RegExp(/xyz/,'i')// 这种写法是错误的 ES6的改变 new RegExp(/ab
1.RegExp构造函数ES5中有两种情况let regex = new RegExp('xyz','i') // 等价于 let regex = /xyz/i let regex = new RegExp(/xyz/i) // 等价于 let regex = /xyz/i
let regex = new RegExp(/xyz/,'i') // 这种写法是错误的 ES6的改变new RegExp(/abc/ig,'i').flags // 第二个参数i会将前面的ig进行覆盖 2.字符串的正则方法
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"] 3.u修饰符
4.RegExp.prototype.unicode 属性
let str = /hello/; let str2 = /hello/u; str.unicode // false str2.unicode // true 5.y修饰符
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(/ad/y) // ['a1'] 'a1a2a3'.match(/ad/gy) // ['a1','a2','a3'] 6.RegExp.prototype.sticky 属性
7.RegExp.prototype.flags 属性
8.s 修饰符:dotAll 模式9.后行断言10.Unicode 属性类11.具名组匹配
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 12.解构赋值和替换
let {groups: {one,two}} = /^(?<one>.*):(?<two>.*)$/u.exec('foo:bar') console.log({one,two}) // {one: 'foo',two: 'bar'} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |