Justin
Justin

Reputation: 85

Using regex to match string1 but not if string1 is accompanied by string 2

I need to only select the strings that contain the word 'Rack', however, if the string contains both 'Rack' and 'Shelf' I don't want it to be selected.

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

I tried something like below but it will still select the last record.

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

Upvotes: 1

Views: 165

Answers (1)

anubhava
anubhava

Reputation: 785406

You can use this regex:

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

RegEx Demo

(?!.*?\bShelf\b) is negative lookahead to fail the match if Shelf is found in the match.

Upvotes: 3

Related Questions