Fred J.
Fred J.

Reputation: 6029

javascript regex to exclude a pattern only if another pattern does not match

A regex is needed in order to exclude sentences with wag[.|on] or ut[i|e] but only if NO sed[.|an] is present and allow all other sentences. any suggestions?
ie. exclude matches that are only wagon or only ute.

I tried /[^wag[on|.]]/ig.test(sentence) but this way will not allow exclusion. I need to select the "yes" sentences only as below.

Given the following sentences:
the sedan is fast <-- yes
other sed. is fast too <-- yes
the wagon is slow <-- no
other wag. is also slow <-- no
the ute is slow <-- no
other uti is also slow <-- no
the wag. and wagon slower then sed. or sedan <-- yes
the uti or ute is slower then sed. or sedan <-- yes
both wag. wagon and uti and ute are slow <-- no
nothing is fast or slow <-- yes

Upvotes: 3

Views: 147

Answers (2)

tsh
tsh

Reputation: 4738

/^(?:.*sed[.|an].*|(?:(?!wag[.|on]|ut[i|e]).)*)$/

you can use (?!) to match a string who do not match some pattern.

Upvotes: 0

Val
Val

Reputation: 22797

this does the trick

function isMatch(input) {
   var regno = /(wag[.|on]|ut[i|e])/gi;
   var regyes = /sed[.|an]/gi;
   return !regno.test(input) || regyes.test(input);
}

result:

enter image description here

Upvotes: 2

Related Questions