Match multiple patterns regularly in any order

I am checking the password for complexity in an ASP.NET MVC3 application. My current requirements are that it must contain at least one uppercase letter, one lowercase letter, one number and no more than three repeated characters. However, I would like to generalize these numbers, as well as add a condition for non-alphanumeric characters.

Currently, I only check the server side, so I can call Regex.IsMatch repeatedly using one regular expression for each condition. I also want to be able to check the client side. because unobtrusive jQuery validation will allow only one regex, I need to combine all five conditions into one template.

I don't know much when it comes to regular expressions, but recently I read a little. I might have missed something simple, but I can’t find a way and multiple templates together like | will be OR them.

+3
source share
1 answer

You can do this (in .NET) with several lookahead statements in one regex:

^(?=.*\p{Lu})(?:.*\p{Ll})(?=.*\d)(?=.*\W)(?!.*(.).*\1.*\1)

will match if all conditions are correct.

^                  # Match the start of the string
(?=.*\p{Lu})       # True if there is at least one uppercase letter ahead
(?=.*\p{Ll})       # True if there is at least one lowercase letter ahead
(?=.*\d)           # True if there is at least one digit ahead
(?=.*\W)           # True if there is at least one non-alnum character ahead
(?!.*(.).*\1.*\1)  # True if there is no character repeated twice ahead

Note that a match will not consume any string characters - if you want the match operation to return the string you are matching, add .*at the end of the regular expression.

In JavaScript, you cannot use Unicode character properties. So instead you can use

^(?=.*[A-Z])(?:.*[a-z])(?=.*\d)(?=.*\W)(?!.*(.).*\1.*\1)

, , ASCII . , . , [A-ZÄÖÜÀÈÌÒÙÁÉÍÓÚ] .. .., , , . , , , RegexOptions.ECMAScript, .NET regex JavaScript ( , !).

+9

Source: https://habr.com/ru/post/1787635/


All Articles