ลอง:
/(?!.*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
regex อื่น ๆ
หากคุณต้องการยกเว้นเฉพาะbarเมื่ออยู่ในภายหลังfooคุณสามารถใช้
/(?!.*foobar)(?=.*foo)^(\w+)$/
แก้ไข
คุณได้อัปเดตคำถามของคุณเพื่อให้เฉพาะเจาะจง
/(?=.*foo(?!bar))^(\w+)$/
การทดสอบใหม่
fooshouldbarpass               # pass
butnotfoobarfail               # fail
fooshouldpassevenwithfoobar    # pass
nofuuhere                      # fail
คำอธิบายใหม่
(?=.*foo(?!bar))ตรวจสอบให้แน่ใจfooว่าพบ แต่ไม่ได้ติดตามโดยตรงbar