负面前瞻正则表达式
Negative look ahead regex
如何匹配前面没有 @
符号的字符串?
/(?!@)(somestring|someotherstring)/
没有产生预期的结果。我在 Sublime: Regular Expressions.cheatsheet
之后的 sublime text 中测试这个
您需要使用 lookbehind:
(?<!@)(somestring|someotherstring)
(?!@)
前瞻将检查 后面的 符号是否不是 @
。
一些more details:
Lookbehind has the same effect [VS: as lookahead], but works backwards. It tells the regex engine to temporarily step backwards in the string, to check if the text inside the lookbehind can be matched there. (?<!a)b
matches a b
that is not preceded by an a
, using negative lookbehind. It doesn't match cab
, but matches the b
(and only the b
) in bed
or debt
.
Negative lookbehind is written as (?<!text)
, using an exclamation point instead of an equals sign.
如何匹配前面没有 @
符号的字符串?
/(?!@)(somestring|someotherstring)/
没有产生预期的结果。我在 Sublime: Regular Expressions.cheatsheet
之后的 sublime text 中测试这个您需要使用 lookbehind:
(?<!@)(somestring|someotherstring)
(?!@)
前瞻将检查 后面的 符号是否不是 @
。
一些more details:
Lookbehind has the same effect [VS: as lookahead], but works backwards. It tells the regex engine to temporarily step backwards in the string, to check if the text inside the lookbehind can be matched there.
(?<!a)b
matches ab
that is not preceded by ana
, using negative lookbehind. It doesn't matchcab
, but matches theb
(and only theb
) inbed
ordebt
.Negative lookbehind is written as
(?<!text)
, using an exclamation point instead of an equals sign.