正则表达式
创建正则表达式
创建正则表达式有两种方式:
let regex = new RegExp('a', 'i');
// 等价于
let regex = /a/i;
正则表达式函数
一种是RegExp实例对象的函数:
test(): 返回值是true 或 false
let word = 'hello world'
let regexp = /hello/
let result = regexp.test(word) // true
exec(): 如何符合正则表达式,返回值是一个数组,否则返回值null
let word = 'hello world'
let regexp = /hello/
let result = regexp.exec(word) // ['hello']
一种是字符串实例对象的函数:
search(): 返回值是返回第一个满足条件的匹配结果在整个字符串中的位置。如果没有任何匹配,则返回-1
let word = 'hello world'
let regexp = /o/
let result = word.search(regexp) // 4
match():返回值跟exec()一样
let word = 'hello world'
let regexp = /o/g
let result = word.match(regexp) // ["o", "o"]
断言
定义
断言:本人认为的意思是可以通过正则将字符串获取符合正则的后面或前面的值。
断言也分为前瞻断言与后瞻断言
前瞻断言
x(?=y) :匹配’x’仅仅当’x’后面跟着’y’
例子:
let word = 'hello3d wrod4d'
let regexp = /\w+(?=3d)/
let resultMatch = word.match(regexp) // ["hello"]
let word = 'hello3d wrod4d'
let regexp = /\w+(?=4d)/
let resultMatch = word.match(regexp) // ["wrod"]
x(?!y):仅仅当’x’后面不跟着’y’时匹配’x’
后瞻断言
(?<=y)x:匹配’x’仅当’x’前面是’y’.
let word = '3dhello 4dwrod4d'
let regexp = /(?<=3d)\w+/
let resultMatch = word.match(regexp) // ["hello"]
let word = 'hello3d wrod4d'
let regexp = /(?<=4d)\w+/
let resultMatch = word.match(regexp) // ["wrod"]
(?<!y)x:仅仅当’x’前面不是’y’时匹配’x’