Password must consist of 8 characters, including 1 uppercase letter, 1 special character, alphanumeric characters

I want the regex to check that

The password must contain eight characters, including one uppercase letter, one special character, and alphanumeric characters.

And here is my validation expression, which is for eight characters, including one uppercase letter, one lowercase letter and one number or special character.

(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[AZ])(?=.*[az]).*$" 

How can I write it for a password that must contain eight characters, including one uppercase letter, one special character, and alphanumeric characters?

+101
c # regex
Feb 28 '12 at 7:20
source share
10 answers

The regular expression that you after this will most likely be huge and a nightmare to maintain especially for people who are not familiar with regular expressions.

I think it would be easier to break your regular expression and do it one at a time. It might take a little more, but I'm sure it would be easier to maintain and debug it. It will also allow you to provide more focused error messages to your users (except for Invalid Password only), which should improve the user experience.

From what I see, you are pretty fluent in regular expression, so I would suggest that giving you regular expressions to do what you need would be useless.

Seeing your comment, I thought about it:

  • There must be eight Long characters: you do not need a regular expression for this. Using the .Length property should be enough.

  • Including one uppercase letter: you can use the regular expression [AZ]+ . If a string contains at least one uppercase letter, this regular expression will give true .

  • One special character: you can use either \W , which will match any character that is not a letter or number, or else, you can use something like this [!@#] To specify your own list of special characters. Note that characters such as $ , ^ , ( and ) are special characters in the regular expression language, so they must be escaped as follows: \$ . In short, you can use \W

  • Alphanumeric characters: Using \w+ must match any letter and number and underscore.

Check out this tutorial for more information.

+128
Feb 28 '12 at 7:32
source share

 ( # Start of group (?=.*\d) # must contain at least one digit (?=.*[AZ]) # must contain at least one uppercase character (?=.*\W) # must contain at least one special symbol . # match anything with previous condition checking {8,8} # length at least 8 characters and also maximum of 8 ) # End of group 

In one line:

 ((?=.*\d)(?=.*[AZ])(?=.*\W).{8,8}) 

Sources:

+101
Feb 28 '12 at 8:35
source share

So many answers .... everything is bad!

Regular expressions do not have the And operator, so it’s quite difficult to write a regular expression that matches valid passwords when reality is determined by something And something else And something else ...

But regular expressions have an OR operator, so just apply the DeMorgan theorem and write a regular expression that matches invalid passwords.

anything less than 8 characters OR all without numbers OR all without capital letters OR all without special characters

So:

 ^(.{0,7}|[^0-9]*|[^AZ]*|[a-zA-Z0-9]*)$ 

If something matches this, then this is the wrong password.

+32
Nov 08 '15 at 1:44
source share

As an example, how can this be done with a readable / supported regular expression.

For a longer regex, you should always use RegexOptions.IgnorePatternWhitespace to allow spaces and comments in the expression for better readability.

 String[] passwords = { "foobar", "Foobar", "Foobar1", "Fooobar12" }; foreach (String s in passwords) { Match password = Regex.Match(s, @" ^ # Match the start of the string (?=.*\p{Lu}) # Positive lookahead assertion, is true when there is an uppercase letter (?=.*\P{L}) # Positive lookahead assertion, is true when there is a non-letter \S{8,} # At least 8 non whitespace characters $ # Match the end of the string ", RegexOptions.IgnorePatternWhitespace); if (password.Success) { Console.WriteLine(s + ": valid"); } else { Console.WriteLine(s + ": invalid"); } } Console.ReadLine(); 
+11
Feb 28 2018-12-12T00:
source share

The answer is to not use regex. These are sets and counting.

Regular expressions are in order.

In your life as a programmer, you will ask to do many things that do not make sense. Learn to dig a level deeper. Find out when the question is incorrect.

The question (if he mentions regular expressions) is incorrect.

Pseudo code (switching between too many languages ​​recently):

 if s.length < 8: return False nUpper = nLower = nAlphanum = nSpecial = 0 for c in s: if isUpper(c): nUpper++ if isLower(c): nLower++ if isAlphanumeric(c): nAlphanum++ if isSpecial(c): nSpecial++ return (0 < nUpper) and (0 < nAlphanum) and (0 < nSpecial) 

Betting on what you read and understand the code above almost instantly. Betting that you took a lot more time with regular expressions, and are less sure that this is correct. Expanding regular expressions is risky. Promoted right away, much less.

Please note that this question is inaccurate. Is the character set ASCII or Unicode, or? My guess, after reading the question, is that at least one lowercase character is assumed. Therefore, I think the last rule adopted should be:

 return (0 < nUpper) and (0 < nLower) and (0 < nAlphanum) and (0 < nSpecial) 

(Changing hats for security reasons is a really annoying / not useful rule.)

Learning to know when a question is incorrect is massively more important than smart answers. The smart answer to the wrong question is almost always wrong.

+9
Sep 23 '15 at 5:52
source share

If you need only one uppercase and a special character, this should work:

 @"^(?=.{8,}$)(?=[^AZ]*[AZ][^AZ]*$)\w*\W\w*$" 
+1
Feb 28 2018-12-12T00: 00Z
source share

The regular expression you were looking for is: /^(?=.*[az])(?=.*[AZ])(?=.*[0-9])(?=.*[!@#\$%\^&\*\[\]"\';:_\-<>\., =\+\/\\]).{8,}$/u .

Example and test: http://regexr.com/3fhr4

+1
Mar 17 '17 at 0:21
source share

This question is starting to be viral, and a lot of interesting suggestions have appeared.

Yes, manual writing is difficult. Thus, it is easier to use a template. Although the given regular expression may not be the most optimal, it will be easier to maintain and / or modify, and the user will have better control over the result. It is possible that I missed something, so any constructive criticism will be useful.

These links can be interesting: match at least 2 digits 2 letters in any order in a string , Regular Expression Language , Group Capture

I use this pattern (?=(?:.*?({type})){({count})}) based on all the regular expression I saw in SO. The next step is to replace the required template ( number , special character ...) and add the configuration for the length.

I made a small class for regex building PasswordRegexGenerator.cs Example:

 string result = new PasswordRegexGenerator ( ) .UpperCase ( 3, -1 ) // ... {3,} .Number ( 2, 4 ) // ... {2,4} .SpecialCharacter ( 2 ) // ... {2} .Total ( 8,-1 ) .Compose ( ); /// <summary> /// Generator for regular expression, validating password requirements. /// </summary> public class PasswordRegexGenerator { private string _elementTemplate = "(?=(?:.*?({type})){({count})})"; private Dictionary<string, string> _elements = new Dictionary<string, string> { { "uppercase", "[AZ]" }, { "lowercase", "[az]" }, { "number", @"\d" }, { "special", @"\W" }, { "alphanumeric", @"\w" } }; private StringBuilder _sb = new StringBuilder ( ); private string Construct ( string what, int min, int max ) { StringBuilder sb = new StringBuilder ( _elementTemplate ); string count = min.ToString ( ); if ( max == -1 ) { count += ","; } else if ( max > 0 ) { count += "," + max.ToString(); } return sb .Replace ( "({type})", what ) .Replace ( "({count})", count ) .ToString ( ); } /// <summary> /// Change the template for the generation of the regex parts /// </summary> /// <param name="newTemplate">the new template</param> /// <returns></returns> public PasswordRegexGenerator ChangeRegexTemplate ( string newTemplate ) { _elementTemplate = newTemplate; return this; } /// <summary> /// Change or update the regex for a certain type ( number, uppercase ... ) /// </summary> /// <param name="name">type of the regex</param> /// <param name="regex">new value for the regex</param> /// <returns></returns> public PasswordRegexGenerator ChangeRegexElements ( string name, string regex ) { if ( _elements.ContainsKey ( name ) ) { _elements[ name ] = regex; } else { _elements.Add ( name, regex ); } return this; } #region construction methods /// <summary> /// Adding number requirement /// </summary> /// <param name="min"></param> /// <param name="max"></param> /// <returns></returns> public PasswordRegexGenerator Number ( int min = 1, int max = 0 ) { _sb.Append ( Construct ( _elements[ "number" ], min, max ) ); return this; } public PasswordRegexGenerator UpperCase ( int min = 1, int max = 0 ) { _sb.Append ( Construct ( _elements[ "uppercase" ], min, max ) ); return this; } public PasswordRegexGenerator LowerCase ( int min = 1, int max = 0 ) { _sb.Append ( Construct ( _elements[ "lowercase" ], min, max ) ); return this; } public PasswordRegexGenerator SpecialCharacter ( int min = 1, int max = 0 ) { _sb.Append ( Construct ( _elements[ "special" ], min, max ) ); return this; } public PasswordRegexGenerator Total ( int min, int max = 0 ) { string count = min.ToString ( ) + ( ( max == 0 ) ? "" : "," + max.ToString ( ) ); _sb.Append ( ".{" + count + "}" ); return this; } #endregion public string Compose () { return "(" + _sb.ToString ( ) + ")"; } } 
0
Sep 24 '15 at 12:51
source share

To check, you can use the class below:

 public class PasswordValidator{ private Pattern pattern; private Matcher matcher; private static final String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[az])(?=.*[AZ])(?=.*[@#$%]).{6,20})"; public PasswordValidator(){ pattern = Pattern.compile(PASSWORD_PATTERN); } /** * Validate password with regular expression * @param password password for validation * @return true valid password, false invalid password */ public boolean validate(final String password){ matcher = pattern.matcher(password); return matcher.matches(); } } 

where 6 and 20 are the minimum and maximum password length.

0
03 Oct '17 at 9:30
source share
 /^(?=.*\d)(?=.*[az])(?=.*[AZ]).{8,}$/ 
-2
Jan 21 '15 at 13:25
source share



All Articles