一尘不染

一个正则表达式,用于匹配没有其他子字符串的子字符串

java

我需要一个匹配blahfooblah但不匹配的正则表达式blahfoobarblah

我希望它只匹配foo及其周围的所有内容,只要不跟在bar后面即可。

我尝试使用此方法:foo.*(?<!bar)这是相当接近的,但它匹配blahfoobarblah。负面的眼光需要匹配任何东西,而不仅仅是障碍。

我使用的特定语言是Clojure,它在后台使用Java正则表达式。

编辑:更具体地说,我也需要它通过blahfooblahfoobarblah但不是blahfoobarblahblah


阅读 224

收藏
2020-09-08

共1个答案

一尘不染

尝试:

/(?!.*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,则可以使用

/(?!.*foobar)(?=.*foo)^(\w+)$/

编辑

您已对问题进行了更新以使其更具体。

/(?=.*foo(?!bar))^(\w+)$/

新测试

fooshouldbarpass               # pass
butnotfoobarfail               # fail
fooshouldpassevenwithfoobar    # pass
nofuuhere                      # fail

新的解释

(?=.*foo(?!bar))确保foo找到a ,但不直接遵循bar

2020-09-08