【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' 字符中的美元数是多少。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值