regexnegative-lookbehindpositive-lookahead

Regex lookahead logical 'OR' - to exclude certain patterns


I've seen a lot of examples of password validation that do a logical AND. For example, password must have

This can be written with regex 'positive lookahead' as:

var includePattern = @"^(?=.*\d)(?=.*[a-zA-z]).{6,15}$"; 
bool tfMatch = Regex.IsMatch("Password1", includePattern); //
if (tfMatch)
    //continue... valid thus far...

My question is I want to EXCLUDE certain groups or patterns, in essence doing a logical 'OR'; For example, let's say i want to match (so as to invalidate password if ANY of the following is true):

Help sought on the excludePattern.. positive lookahead? negative lookahead?

var excludePattern = @"^( ...xxx...  $"; //<== **** what goes in here??
bool tfMatch = Regex.IsMatch("Pass 666 word", excludePattern); //
if (tfMatch)
    //DONT continue... contains excluded

I am using c# regex, but any flavor will do to get started.


Solution

  • Just like you can use multiple positive lookaheads to check that a string fulfills multiple positive patterns, you can alternate inside a negative lookahead to check that none of the alternated patterns inside the lookahead are matched by the string. For example, for your

    AT LEAST one SPACE FOUND (OR)

    at least one single-quote found (OR)

    at least one double-quote found (OR)

    the string "666" number of the beast

    You can use

    ^(?!.* |.*'|.*"|.*666)<rest of your pattern>
    

    https://regex101.com/r/u9BoIl/1