RegExp
- RegExp 在ES9中新增
dotAll(点匹配)
- 判断有没有开启dotAll
named captured groups(命名分组捕捉)
ES5
- ES9
loodbehind assert(后行断言)
- 后行断言
- 后行断言
- ES6-ES10学习幅员
RegExp 在ES9中新增
- dotAll
- 命名分组捕捉
- 后行断言
dotAll(点匹配)
正则中的点就是dotAll
,都是匹配任意字符,然而很多字符是无奈匹配的。例如:
- 四个字节的
UTF-16
的字符 - 行终止符
\\n
\\r
换行 回车
console.log(/foo.bar/.test('foo\nbar'))//falseconsole.log(/foo.bar/.test('fooabar'))// true
加上s
能够匹配换行符
console.log(/foo.bar/s.test('foo\nbar'))// true
加上s
能够匹配换行符,加上u
就能够匹配4位的UTF-16
字符,点的性能就全能了
console.log(/foo.bar/us.test('foo\nbar'))
判断有没有开启dotAll
应用flags
属性判断,如果没有开启就是false
const r = /foo.bar/console.log(r.dotAll)// falseconsole.log(r.flags)// 空const re = /foo.bar/sconsole.log(re.dotAll)// trueconsole.log(re.flags)// s
named captured groups(命名分组捕捉)
之前分组捕捉有,然而命名的分组捕捉刚有
ES5
如何取到字符串中匹配的年月日?
// 先看一下match匹配进去的值有哪些?console.log("2019-06-07".match(/(\d{4})-(\d{2})-(\d{2})/))// ["2019-06-07", "2019-06-07", "2019", "06", "07", index: 0, input: "2019-06-07", groups: undefined]// 残缺匹配// 第一个括号分组// 第二个括号分组// 第三个括号分组// index 从第几个字符开始匹配到的// input 残缺的输出字符串// groups 目前位空,一会就晓得用法了const t = "2019-06-07".match(/(\d{4})-(\d{2})-(\d{2})/)console.log(t[1]) //2019console.log(t[2]) //06console.log(t[3]) //07
下面的办法,如果数据简单的时候不好写,况且数组还要数第几个,那么加一个名字会比拟好
ES9
// 在括号外面写 ?<命名key>const T = "2019-06-07".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/)console.log(T)// ["2019-06-07", "2019", "06", "07", index: 0, input: "2019-06-07", // groups: {day: "07", month: "06", year: "2019"}]// 这个时候groups外面有值了,而且用命名的key能够取到console.log(T.groups.year) //2019console.log(T.groups.month) //06console.log(T.groups.day) //07
loodbehind assert(后行断言)
后行断言都有,ES9
刚有的后行断言
后行断言
js
始终是后行断言的
let test = 'hello world'console.log(test.match(/hello(?=\sworld)/))// 前面的括号不是分组匹配,是后行断言// 先遇到一个条件
后行断言
然而我要晓得world
之前的那个是hello
,就是后行断言
ES9
这个能力补齐了
console.log(test.match(/(?<=hello\s)world/))// (?<=hello\s) 是判断world后面是hello加空格console.log(test.match(/(?<!hell2\s)world/))// ! 示意不等于// \1示意捕捉匹配