JavaScript

ES6学习第四节:RegExp正则表达式

2019-01-18  本文已影响0人  ChangLau

声明正则表达式

// 参数是字符串
var regex = new RegExp('xyz', 'i')
var regex = /xyz/i
// 参数为正则表达式
var regex = new RegExp(/xyz/i)
// ES5不支持使用正则表达式声明后,在传入第二个参数。这种方式在ES6开始提供支持,后面声明的修饰符会覆盖第一个参数中的修饰符
var regex = new RegExp(/xyz/i, 'g')

返回表达式修饰符

var regex = new RegExp(/xyz/i, 'g')
console.log(regex.flags)
// g

是否设置了U修饰符,U修饰符主要解决四字节UTF-16匹配问题

var regex = new RegExp(/xyz/i, 'g')
console.log(regex.unicode)

y修饰符的作用与g修饰符类似,也是全局匹配,后一次匹配都从上一次匹配成功的下一个位置开始。不同之处在于,g修饰符只要剩余位置中存在匹配就可,而y修饰符确保匹配必须从剩余的第一个位置开始

var str = 'aaa_aa_a'
var reg1 = /a+/g
var reg2 = /a+/y
console.log(reg1.exec(str))
console.log(reg1.exec(str))
console.log(reg1.exec(str))
console.log(reg1.exec(str))
// [ 'aaa', index: 0, input: 'aaa_aa_a', groups: undefined ]
// [ 'aa', index: 4, input: 'aaa_aa_a', groups: undefined ]
// [ 'a', index: 7, input: 'aaa_aa_a', groups: undefined ]
// null
console.log(reg2.exec(str))
console.log(reg2.exec(str))
// [ 'aaa', index: 0, input: 'aaa_aa_a', groups: undefined ]
// null

lastIndex属性指定每次搜索的开始位置,g修饰符从这个位置开始向后搜索,直到发现匹配为止。y修饰符同样遵守lastIndex属性,但是要求必须在lastIndex指定的位置发现匹配。

var regex = /a/g
regex.lastIndex = 2
// 从指定位置向后搜索
console.log(regex.exec('xaya'))
// [ 'a', index: 3, input: 'xaya', groups: undefined ]

var regex1 = /a/y
regex1.lastIndex = 2
// 指定位置没有发现匹配
console.log(regex1.exec('xaya'))
// null

//指定位置发现匹配
regex1.lastIndex = 3
console.log(regex1.exec('xaya'))
// [ 'a', index: 3, input: 'xaya', groups: undefined ]

sticky属性表示是否设置了y修饰符

var regex1 = /a/y
console.log(regex1.sticky);
// true

source返回正则表达式正文、flags返回正则表达式修饰符

// ES5 的 source 属性
// 返回正则表达式的正文
/abc/ig.source
// "abc"

// ES6 的 flags 属性
// 返回正则表达式的修饰符
/abc/ig.flags
// 'gi'

ES5中, '.'可以代表任意单个字符。但是有两个例外,一个是四字节的UTF-16字符,可以使用U修饰符来解决,另一个是行终止符。(\n、\r)

var str = 'hello\nworld'
var reg = /hello.world/
// .不能识别\n
console.log(reg.exec(str))
// null

// s修饰符,使得.可以匹配任意单个字符。
var reg = /hello.world/s
console.log(reg.exec(str))
// [ 'hello\nworld', index: 0, input: 'hello\nworld', groups: undefined ]
console.log(reg.dotAll, reg.flags)
// true 's'
上一篇 下一篇

猜你喜欢

热点阅读