使用正则表达式匹配string1但不是如果string1伴随字符串2

时间:2015-07-30 17:43:15

标签: regex

我只需要选择包含单词'Rack'的字符串,但是,如果字符串同时包含'Rack'和'Shelf',我不希望它被选中。

blah/blah/Rack 1/Box 5/Row 2/Cell 3
blah/blah/Rack 2/Box 4/Row 2/Cell 3
blah/blah/Rack 4/Box 3/Row 2/Cell 3 
blah/blah/Shelf 1/Rack 1/Box 1/Row 2/Cell 3
blah/blah/Box 3/Row 2/Cell 3

我尝试了类似下面的内容,但它仍会选择最后一条记录。

(^((?!Shelf).)*$)

1 个答案:

答案 0 :(得分:3)

您可以使用此正则表达式:

^(?!.*?\bShelf\b).*?\bRack\b.*$

RegEx Demo

如果在匹配中找到(?!.*?\bShelf\b),则

Shelf为比赛失败,为负面预测。