2

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.

js_Dudley
  • 23
  • 1
  • 3

3 Answers3

3

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);
Bob Vale
  • 18,094
  • 1
  • 42
  • 49
  • 1
    This works perfectly. Thank you. I just wanted to know if I wanted to add additional words with lizard should I just separate them with a "|" after lizard eg. (?<!lizard|mouse.*)(?:dog|cat|lion)(?!.*lizard|mouse) ??? – js_Dudley Jan 30 '12 at 14:52
  • 1
    @js_Dudley you probably want to use a bracket to make sure the if compares the correct words so `(?<!(lizard|mouse).*)(?:dog|cat|lion)(?!.*(lizard|mouse))` – Bob Vale Jan 30 '12 at 17:26
  • This will not work in all flavors of regex ... many of them require lookaheads to be fixed-length, and the `.*` inside the lookahead group causes an error. This similar, but slightly different, approach will work in that case: https://stackoverflow.com/a/406408 ... but I guess this works in vb.net – Aaron Wallentine Oct 13 '19 at 03:41
2

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])*$

Muxecoid
  • 1,193
  • 1
  • 9
  • 22
0

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
Iridium
  • 23,323
  • 6
  • 52
  • 74