仅当前面或后面没有另一个模式时才匹配模式 [英] Match a pattern only when NOT preceded or followed by another pattern
本文介绍了仅当前面或后面没有另一个模式时才匹配模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道最简单的方法是使用 [^a]b[^c]
(对于 b
前面没有 a
和后面没有 c
),但我也想在 begining 或 end 时匹配 b
> 的字符串.
I know the naive way would be to use [^a]b[^c]
(for b
not preceded by a
and not followed by c
), but I also want to match b
when it is at the beginning or at the end of the string.
推荐答案
您使用的是哪种正则表达式?如果您可以使用 Perl 正则表达式,则可以使用负向后视和负向前瞻:
What sort of regex are you using? If you can use Perl regex, you can use a negative lookbehind and negative lookahead:
(?<!a)b(?!c)
否则,您通常能做的最好的事情是:
Otherwise the best you can do is typically:
([^a]|^)b([^c]|$)
即b 前面是除 a 或 行的开头之外的任何内容,然后是除 c 或 行结尾以外的任何内容.
i.e. the b is preceded by anything but a or the start of the line, and followed by anything but c or the end of the line.
这篇关于仅当前面或后面没有另一个模式时才匹配模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文