正则表达式的先行断言(lookahead)和后行断言(lookbehind)
均是匹配位置,在匹配过程中,不占用字符,所以被称为零宽。
(?=pattern)
零宽正向先行
断言(zero-width positive lookahead assertion)紧接该位置之后的字符序列能够匹配
pattern
如替换后面紧跟
c
的ab
为xx
:1
'abcabdabe'.replace(/ab(?=c)/g, 'xx'); // xxcabdabe
(?!pattern)
零宽负向先行
断言(zero-width negative lookahead assertion)紧接该位置之后的字符序列不能匹配
pattern
如替换后面不为
c
的ab
为xx
:1
'abcabdabe'.replace(/ab(?!c)/g, 'xx'); // abcxxdxxe
(?<=pattern)
零宽正向后行
断言(zero-width positive lookbehind assertion)紧接该位置之前的字符序列能够匹配
pattern
如替换前面为
a
的bc
为xx
:1
'abcdbcebc'.replace(/(?<=a)bc/g, 'xx'); // axxdbcebc
(?<!pattern)
零宽负向后行
断言(zero-width negative lookbehind assertion)紧接该位置之前的字符序列不能匹配
pattern
如替换后面不为
a
的bc
为xx
:1
'abcdbcebc'.replace(/(?<!a)bc/g, 'xx'); // abcdxxexx
另:非捕获分组(?:p)
括号
是提供分组功能,如果只想要括号
最原始的功能,但不会引用它,即既不在 API 里引用,也不在正则里反向引用。此时可以使用非捕获分组(?:p)
1 | 'abcde'.replace(/(ab)c(de)/g, '$1'); // ab |