How to negate specific word in regex?
我知道我可以在[^bar]
否定字符组,但是我需要一个正则表达式,其中否定适用于特定单词 - 所以在我的示例中,我如何否定实际的"bar"
而不是"any chars in bar"
?
一个很好的方法是使用负面看法:
^(?!.*bar).*$
Unless performance is of utmost concern, it's often easier just to run your results through a second pass, skipping those that match the words you want to negate.
Regular expressions usually mean you're doing scripting or some sort of low-performance task anyway, so find a solution that is easy to read, easy to understand and easy to maintain.
The following regex will do what you want (as long as negative lookbehinds and lookaheads are supported), matching things properly; the only problem is that it matches individual characters (ie each match is a single character rather than all characters between two consecutive "bar"s), possibly resulting in a potential for high overhead if you're working with very long strings.
b(?!ar)|(?<!b)a|a(?!r)|(?<!ba)r|[^bar]
链接地址: http://www.djcxy.com/p/13442.html
上一篇: 正则表达式在第一场比赛中停止
下一篇: 如何否定正则表达式中的特定单词?