3

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

  • AT LEAST one digit (AND)
  • AT LEAST one character (AND)
  • length between 6 and 15

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):

  • 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

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.

joedotnot
  • 4,810
  • 8
  • 59
  • 91
  • Just negative lookahead for an alternation between those patterns you want to exclude? – CertainPerformance Apr 12 '19 at 02:17
  • CertainPerformance.. don't know, no idea where to even start.. as good as a newbie when it comes to regex. If my question is clear, please write as an answer. it may help others too. – joedotnot Apr 12 '19 at 02:22

1 Answers1

0

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

Community
  • 1
  • 1
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320