简体   繁体   中英

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

  • 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM