我需要一个匹配blahfooblah但不匹配的正则表达式blahfoobarblah
blahfooblah
blahfoobarblah
我希望它只匹配foo及其周围的所有内容,只要不跟在bar后面即可。
我尝试使用此方法:foo.*(?<!bar)这是相当接近的,但它匹配blahfoobarblah。负面的眼光需要匹配任何东西,而不仅仅是障碍。
foo.*(?<!bar)
我使用的特定语言是Clojure,它在后台使用Java正则表达式。
编辑:更具体地说,我也需要它通过blahfooblahfoobarblah但不是blahfoobarblahblah。
blahfooblahfoobarblah
blahfoobarblahblah
/(?!.*bar)(?=.*foo)^(\w+)$/
blahfooblah # pass blahfooblahbarfail # fail somethingfoo # pass shouldbarfooshouldfail # fail barfoofail # fail
NODE EXPLANATION -------------------------------------------------------------------------------- (?! look ahead to see if there is not: -------------------------------------------------------------------------------- .* any character except \n (0 or more times (matching the most amount possible)) -------------------------------------------------------------------------------- bar 'bar' -------------------------------------------------------------------------------- ) end of look-ahead -------------------------------------------------------------------------------- (?= look ahead to see if there is: -------------------------------------------------------------------------------- .* any character except \n (0 or more times (matching the most amount possible)) -------------------------------------------------------------------------------- foo 'foo' -------------------------------------------------------------------------------- ) end of look-ahead -------------------------------------------------------------------------------- ^ the beginning of the string -------------------------------------------------------------------------------- ( group and capture to \1: -------------------------------------------------------------------------------- \w+ word characters (a-z, A-Z, 0-9, _) (1 or more times (matching the most amount possible)) -------------------------------------------------------------------------------- ) end of \1 -------------------------------------------------------------------------------- $ before an optional \n, and the end of the string
如果您只想排除紧接bar其后的时间foo,则可以使用
bar
foo
/(?!.*foobar)(?=.*foo)^(\w+)$/
您已对问题进行了更新以使其更具体。
/(?=.*foo(?!bar))^(\w+)$/
fooshouldbarpass # pass butnotfoobarfail # fail fooshouldpassevenwithfoobar # pass nofuuhere # fail
(?=.*foo(?!bar))确保foo找到a ,但不直接遵循bar
(?=.*foo(?!bar))