【ES9系列】RegExp dotAll模式、命名分组捕获、后行断言

dotAll 模式

正则表达式中,(.)可以匹配任意字符,但是4个字节的 utf16 和\n \r 换行、回车终止符不能用(.)匹配

console.log(/foo.bar/.test('foo\nbar')); // false
console.log(/foo.bar/.test('fooabar')); // true

// 使用 dotAll模式匹配
console.log(/foo.bar/s.test('foo\nbar')); // true

验证是否开启dotAll 模式

const re = /foo.bar/s
// 判断是否启用dotAll模式
console.log(re.dotAll) // true

flags 方法,判断正则表达式使用了哪些修饰符

const re = /foo.bar/sgiu
console.log(re.flags) // gisu

正则表达式的 match()方法及返回说明

console.log('2019-06-07'.match(/(\d{4})-(\d{2})-(\d{2})/))
// ["2019-06-07", "2019", "06", "07", index: 0, input: "2019-06-07", groups: undefined]
// [完整匹配,第一个分组,第二个分组,第三个分组,正则从字符串的第几个字符开始匹配到的,完整的输入字符串,分组]

const t = '2019-06-07'.match(/(\d{4})-(\d{2})-(\d{2})/)
console.log(t[1]) // 2019
console.log(t[2]) // 06
console.log(t[3]) // 07

命名分组捕获

用 ?<分组name> 给分组命名 

const t = '2019-06-07'.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/)
console.log(t)

分组命名后,groups返回值发生了变化

这样一来就可以通过命名的分组捕获来对匹配数据进行读取

const t = '2019-06-07'.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/)
console.log(t.groups.year) // 2019
console.log(t.groups.month) // 06
console.log(t.groups.day) // 07

后行断言 (?<)  先行断言(?)

结合先行断言和后行断言模式一起使用:= 等于      !不等于         \1 捕获匹配

// 先行断言 模式:匹配到hello后开始匹配后边的 空格和world,从左到右匹配
let test = 'hello world'
console.log(test.match(/hello(?=\sworld)/));
// ["hello", index: 0, input: "hello world", groups: undefined]

// 后行断言 模式:判断 world 前边是 hello
// ?< 采用后行断言
console.log(test.match(/(?<=hello\s)world/))
// ["world", index: 6, input: "hello world", groups: undefined]
console.log(test.match(/(?<!hello\s)world/)) // null

思考:

1、请把‘$foo %foo foo’ 字符串中前边是$ 符号的foo 替换成bar.

2、请提取 '$1 is worth about ¥123' 字符中的美元数是多少。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章