js_Dudley
js_Dudley

Reputation: 23

Regex: How to make IsMatch to fail if a particular word matches in string

I have to search a string for a few words eg, dog, cat, lion but I want regex to fail if lizard is found in the string even if it contains cat, dog or lion.

ismatch(pass) "dog|cat|lion" "This is not your average cat!"

ismatch (fail) [my regex statement] "This is not your average cat! It's a lizard."

[my regex statement] - here the regex statement is unknown, can you please help me to write this statement?

Word spaces and boundaries or lower/uppercase is not a concern. I run the string through

Replace(" ", "").Trim(" ").ToLower 

before handover to Regex.

Upvotes: 2

Views: 3748

Answers (3)

Bob Vale
Bob Vale

Reputation: 18474

Try this using negative lookahead and negative look behind

(?<!lizard.*)(?:dog|cat|lion)(?!.*lizard)

If you use the Regex option ignore case you don't need to call tolower. You can specify it by adding (?i) to the beginning of the regex string.

After comment by js_dudley here is a way to build the string up

var exclude=new string[] { "lizard","eagle"};
var include=new string[] {"dog","cat","lion"};
var regexString=string.Format(
                                "(?<!({0}).*)(?:{1})(?!.*({0}))",
                                string.Join("|",exclude),
                                string.Join("|",include)
                             );
var regex=new Regex(regexString);

Upvotes: 4

Muxecoid
Muxecoid

Reputation: 1241

If lookahead is not possible for some reason you can try this ugly trick: (dog|cat|lion)([^l]|l[^i]|li[^z]|liz[^a]|liza[^r]|lizar[^d])*$

Upvotes: 2

Iridium
Iridium

Reputation: 23721

Is it not acceptable to simply use (syntax may not be perfect):

If nonLizardAnimalsRegex.IsMatch(yourString) And Not lizardRegex.IsMatch(yourString) Then
    ' String contains an animal but not "lizard"
End If

Upvotes: 0

Related Questions