blog
blog copied to clipboard
正则表达式之断言
正则表达式--断言
Positive Lookbehind
-
(?<=) #断言要匹配的文本前缀
let str = 'qwert&code=1243&qerfvs=6577';
str.replace(/(?<=code=)\d+/,'4321'); // "qwert&code=4321&qerfvs=6577"
Negative Lookbehind
-
(?<!) #断言位置不能匹配的文本前缀
"(?<!(T|t)he\s)(cat)" => The cat sat on cat.
Positive Lookahead
-
(?=) #断言要匹配的文本后缀
"(T|t)he(?=\sfat)" => The fat cat sat on the mat.
// 匹配 紧跟fat的 The或the
Negative Lookahead
-
(?!) #断言位置不能匹配的文本后缀
"(T|t)he(?!\sfat)" => The fat cat sat on the mat.
// 匹配文本后面不紧跟fat的The 或the
- https://regexper.com/
- https://regexr.com/
总结
- X(?=Y) Positive lookahead X if followed by Y
- X(?!Y) Negative lookahead X if not followed by Y
- (?<=Y)X Positive lookbehind X if after Y
- (?<!Y)X Negative lookbehind X if not after Y