Thử:
/(?!.*bar)(?=.*foo)^(\w+)$/
Kiểm tra:
blahfooblah # pass
blahfooblahbarfail # fail
somethingfoo # pass
shouldbarfooshouldfail # fail
barfoofail # fail
Giải thích cụm từ thông dụng
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 khác
Nếu bạn chỉ muốn loại trừ barkhi nó diễn ra ngay sau đó foo, bạn có thể sử dụng
/(?!.*foobar)(?=.*foo)^(\w+)$/
Biên tập
Bạn đã cập nhật câu hỏi của mình để làm cho nó cụ thể.
/(?=.*foo(?!bar))^(\w+)$/
Các bài kiểm tra mới
fooshouldbarpass # pass
butnotfoobarfail # fail
fooshouldpassevenwithfoobar # pass
nofuuhere # fail
Giải thích mới
(?=.*foo(?!bar))đảm bảo rằng a foođược tìm thấy nhưng không được theo dõi trực tiếpbar