正则表达式注意事项

发布时间 2023-03-22 21:15:43作者: DAmarkday

问题

正则表达式一段时间不常用就经常忘掉,这里记录一下容易忘掉的知识点。

?=和?:和?!和?<=和?<!

要理解?=和?!,首先需要理解 前瞻后顾负前瞻负后顾 四个概念:

// 前瞻:
exp1(?=exp2) 查找包含exp1和exp2的字段,只会返回符合规则的exp1
// 后顾:
(?<=exp2)exp1 查找位于exp2后面的exp1,只返回exp1
// 负前瞻:
exp1(?!exp2) 查找exp1,同时后面不是exp2的exp1,只返回exp1
// 负后顾:
(?<!exp2)exp1 查找exp1,但前面不是exp2的exp1,只返回exp1

// 例子
// ?=
"hello---hello666hellomm".replace(/hello(?=(\d+))/g,"")   // 'hello---666hellomm'

// ?<=
"hello---hello666hellomm".replace(/(?<=(\d+))hello/g,"")  // 'hello---hello666mm'

// ?!
"hello---hello666hellomm".replace(/hello(?!(\d+))/g,"")   // '---hello666mm'

// ?<!
"hello---hello666hellomm".replace(/(?<!(\d+))hello/g,"")  // '---666hellomm'

// ?:
"hello---hello666hellomm".replace(/(hello(\d+))/g,"$2")   // 'hello---666hellomm'
"hello---hello666hellomm".replace(/(?:hello(\d+))/g,"$1") // 'hello---666hellomm'
// 第一个例子,用了两个括号,匹配了hello+数字,$2代表留下被第二个括号捕获的内容(数字)。
// 第二个例子在第一个括号内加了 ?:,就消除掉了他的捕获,那么可以直接用$1来替换数字了。


要理解?:则需要理解捕获分组和非捕获分组的概念:
()表示捕获分组,()会把每个分组里的匹配的值保存起来,使用$n(n是一个数字,表示第n个捕获组的内容)
(?:)表示非捕获分组,和捕获分组唯一的区别在于,非捕获分组匹配的值不会保存起来

文章地址: