一个正则expression式来匹配没有被某个其他子string跟踪的子string
我需要一个匹配blahfooblah但不blahfoobarblah正则expression式
我希望它只匹配foo和foo周围的所有东西,只要不跟着吧。
我尝试使用这个: foo.*(?<!bar) ,它非常接近,但它匹配blahfoobarblah 。 负面的背后需要匹配任何东西,而不仅仅是酒吧。
我正在使用的特定语言是Clojure,它使用Java下的正则expression式。
编辑:更具体地说,我也需要它通过blahfooblahfoobarblah但不blahfoobarblahblah 。
尝试:
/(?!.*bar)(?=.*foo)^(\w+)$/
testing:
blahfooblah # pass blahfooblahbarfail # fail somethingfoo # pass shouldbarfooshouldfail # fail barfoofail # fail
正则expression式解释
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 (az, AZ, 0-9, _) (1 or more times (matching the most amount possible)) -------------------------------------------------------------------------------- ) end of \1 -------------------------------------------------------------------------------- $ before an optional \n, and the end of the string
其他正则expression式
如果你只想在foo之后直接排除它,你可以使用
/(?!.*foobar)(?=.*foo)^(\w+)$/
编辑
你对你的问题进行了更新,使其具体。
/(?=.*foo(?!bar))^(\w+)$/
新的testing
fooshouldbarpass # pass butnotfoobarfail # fail fooshouldpassevenwithfoobar # pass nofuuhere # fail
新的解释
(?=.*foo(?!bar))确保findfoo ,但不会直接跟在bar
为了匹配一个不以bar开头的东西,请尝试
foo(?!bar)
你的负面后台的版本是有效的“匹配一个foo然后是不以bar结束的东西”。 .*匹配所有barblah ,并且(?<!bar)回头查看lah并检查它是否与bar不匹配,因此整个模式匹配。
改用负面观察:
\s*(?!\w*(bar)\w*)\w*(foo)\w*\s*
这对我有用,希望它有帮助。 祝你好运!
您的具体匹配请求可以匹配:
\w+foo(?!bar)\w+
这将匹配blahfooblahfoobarblah但不blahfoobarblahblah 。
foo.*(?<!bar)正则expression式的问题是foo.*(?<!bar)之后的.* 。 它可以匹配包含任何字符在内的任何字符。
你写了一个评论,build议你喜欢这个工作匹配一个string中的所有单词而不是整个string本身。
而不是在评论中混合所有这些,我把它作为一个新的答案。
新的正则expression式
/(?=\w*foo(?!bar))(\w+)/
示例文本
foowithbar fooevenwithfoobar notfoobar foohere notfoobarhere butfooisokherebar notfoobarhere andnofuu needsfoo
火柴
foowithbar fooevenwithfoobar foohere butfooisokherebar needsfoo