Password strength regex [duplicate] - c#

This question already has answers here:
Regex to validate password strength
(11 answers)
Closed 9 years ago.
I am trying to replace our password validation with a simple RegEx in my asp.net project which uses regularexpression validator.
Here is the password restrictions:
Password should be of minimum 6 chars in length and maximum 15
It should have at least one letter (any case)
It should have at least one digit
It should have at least one special character.
I am n00b at regex and this is the only type of question where i ask for spoon feeding ;)
I tried below regex but it fails in few cases.
string re1="([a-z])"; // Any Single Word Character (Not Whitespace) 1
string re2=".*?"; // Non-greedy match on filler
string re3="."; // Uninteresting: c
string re4=".*?"; // Non-greedy match on filler
string re5="."; // Uninteresting: c
string re6=".*?"; // Non-greedy match on filler
string re7="(.)"; // Any Single Character 1
string re8="(\\d)"; // Any Single Digit 1
Regex r = new Regex(re1+re2+re3+re4+re5+re6+re7+re8,RegexOptions.IgnoreCase|RegexOptions.Singleline);
Match m = r.Match(txt)

Use a pattern like this:
^(?=.*[a-z])(?=.*[0-9])(?=.*[...]).{6,15}$
Where you can replace the [...] with whatever characters you want to accept as 'special characters'.
To break this down a bit:
The start (^) and end ($) anchors ensure there are no leading or trailing characters in the input. This is necessary to ensure the maximum length is enforced.
The .{6,15} bit matches 6 to 15 of any character.
The (?=...) is a lookahead. It ensures that the position being matched is followed by whatever pattern appears inside.
The .*[a-z] means any number of characters followed by a single Latin letter.
Similarly, .*[0-9] matches any number of characters followed by a decimal digit, and .*[...] matches any number of characters followed by one of your 'special characters'.
So collectively, the chain of (?=.*[a-z])(?=.*[0-9])(?=.*[...]) means that all three of these patterns must be present within the following string, in any order.

I'm new to this also and I found a post on validating filenames that should work the same.
if(preg_match('/^[a-z0-9-_]+$/',$file_name))
{
echo 'good filename';
}
else
{
echo ' The file name can only contain "a-z", "0-9", "_", and "-"';
}
This checks to see if it contains certain characters which you can use to detect numbers and letters in a password. Also, if I were you I would also compare the password against a list of common passwords such as "password" "password123" etc.

Related

Regularexpression for duplicate pattern

I am trying to write a regex to handle these cases
contains only alphanumeric with minimum of 2 alpha characters(numbers are optional).
only special character allowed is hyphen.
cannot be all same letter ignoring hyphen.
cannot be all hyphens
cannot be all numeric
My regex: (?=[^A-Za-z]*[A-Za-z]){2}^[\w-]{6,40}$
Above regex works for most of the scenarios except 1) & 3).
Can anyone suggest me to fix this. I am stuck in this.
Regards,
Sajesh
Rule 1 eliminates rule 4 and 5: It can neither contain only hyphens, nor only digits.
/^(?=[a-z\d-]{6,40}$)[\d-]*([a-z]).*?(?!\1)[a-z].*$/i
(?=[a-z\d-]{6,40}$) look ahead for specified characters from 6 to 40
([a-z]).*?(?!\1)[a-z] checks for two letters and at least one different
See this demo at regex101
This pattern with i flag considers A and a as the "same" letter (caseless matching) and will require another alpbhabet. For case sensitive matching here another demo at regex101.
You can use
^(?!\d+$)(?!-+$)(?=(?:[\d-]*[A-Za-z]){2})(?![\d-]*([A-Za-z])(?:[\d-]*\1)+[\d-]*$)[A-Za-z\d-]{6,40}$
See the regex demo. If you use it in C# or PHP, consider replacing ^ with \A and $ with \z to make sure you match the entire string even in case there is a trailing newline.
Details:
^ - start of string
(?!\d+$) - fail the match if the string only consists of digits
(?!-+$) - fail the match if the string only consists of hyphens
(?=(?:[\d-]*[A-Za-z]){2}) - there must be at least two ASCII letters after any zero or more digits or hyphens
(?![\d-]*([A-Za-z])(?:[\d-]*\1)+[\d-]*$) - fail the match if the string contains two or more identical letters (the + after (?:[\d-]*\1) means there can be any one letter)
[A-Za-z\d-]{6,40} - six to forty alphanumeric or hyphen chars
$ - end of string. (\z might be preferable.)

My regular expresiion is not working in C#

I need a regex that checks if a password contains at least one Lowercase letter, at least one Upper case letter, at least two numbers and at least one of(_*&$). This is a MVC project.
This what i have
[RegularExpression(#"(?=\.\*\\d{2})(?=\./*[a-z])(?=\.\*[A-Z])(?=.*[_*&$])", ErrorMessage = "The password must contain at least 1 letter, 2 digits and a special symbol (_*&$)")]
There are a lot of issues with the current regex:
You escaped . and *, and now they denote literal . and * chars, while you wanted to use them as special regex metacharacters
To match at least two digits, you can't just use a \d{2} pattern because it does not match non-consecutive digits, you need \d.*\d or a more efficient (?:\D*\d){2}
You are only using lookaheads, non-consuming patterns, but the RegularExpressionAttribute requires a full string to match the pattern.
Thus, you need
#"^(?=(?:\D*\d){2})(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=[^_*&$]*[_*&$]).*"
Details
^ - start of string
(?=(?:\D*\d){2}) - two not necessarily consecutive digits
(?=[^a-z]*[a-z]) - at least one lowercase ASCII letter
(?=[^A-Z]*[A-Z]) - at least one uppercase ASCII letter
(?=[^_*&$]*[_*&$]) - at least one special char from the _*&$ set
.* - the whole string (with no line breaks) (it gets consumed).

Regex pattern is not correct

I have the following regex to match this:
U$MichaelU$P#$asdqwe123P#$ - this is correct; the other two are not
U$NameU$P#$PasswordP#$
U$UserU$P#$ad2P#$
A registration is valid when:
The username is surrounded by "U$"
The username needs to be minimum 3 characters long, start with an uppercase letter, followed only by lowercase letters
The password is surrounded by "P#$"
The password needs to start with minimum 5 alphabetical letters (not including digits) and must end with a digit
My regex is
#"^(U\S)([A-z][a-z]{3,})\1(P#\S)([a-z]{5,}[^\d])([\d]+)\3$"
The problem is that it matches the first one but when I submit to the judge it passes first 2 test but the rest it breaks, could you please tell me where is my mistake.
Hello your regex must be
#"^(U\S)([A-Za-z]{3,})\1(P#\S)([A-Za-z0-9]{5,})\3$"
it works for you

Writing a proper regex to allow number and only combinations of letters and numbers mixed up

I have a string example which looks like this:
51925120851209567
The length of the string and numbers may vary, however I want to only enable the string to contain just either numbers, or for it to be a combination of letters and numbers. For example a valid one would be something like this:
B0031Y4M8S // contains combination of letters and numbers without white space
Invalid regex would be:
Does not apply // this one contains white spaces and has only letters
To summarize things up, the regex should allow only these combinations:
51925120851209567 // contains only numbers and is valid
B0031Y4M8S // contains combination of numbers and letters and is valid as well
Everything else is invalid...
The current solution that I have covers only for the string to be a set of integers and nothing else... However I'm not really sure how to filter out combination of numbers and letters without white spaces and special charachters to be valid as well for the regex?
Regex regex = new Regex("^[0-9]+$");
if (regex.IsMatch(parameter))
{
// allow if statement to pass if the regex matches
}
Can someone help me out ?
You may use
^(?![A-Za-z]+$)[0-9A-Za-z]+$
It matches 1+ alphanumeric chars but will fail a match if all string consists of just letters.
Details
^ - start of a string
(?![A-Za-z]+$) - a negative lookahead that fails the match if there are 1+ ASCII letters followed with the end of string immediately to the right of the current location
[0-9A-Za-z]+ - 1+ ASCII letters
$ - end of string.
See the regex demo.
#The fourth bird's answer will almost get you there. I'm no regex expert, but an easy way to get you what you want would be to use:
Regex regex = new Regex("^[a-zA-Z0-9]+$");
This will get you the first level of exclusion. If it passes that, then check with:
Regex regex = new Regex("^[a-zA-Z]+$");
If it matches that, then you know it's only alphabetical characters and you can skip it. I'm sure there's a better way to code golf this one out, but this should work for now if you're in a crunch.

Better way to write this RegEx?

I have this password regex for an application that is being built its purpose is to:
Make sure users use between 6 - 12 characters.
Make sure users use either one special character or one number.
Also that its case insensitive.
The application is in .net I have the following regex:
I have the following regex for the password checker, bit lengthy but for your viewing if you feel any of this is wrong please let me know.
^(?=.*\d)(?=.*[A-Za-z]).{6-12}$|^(?=.*[A-Za-z])(?=.*[!#$%&'\(\)\*\+-\.:;<=>\?#\[\\\]\^_`\{\|\}~0x0022]|.*\s).{6,12}$
Just a break down of the regex to make sure your all happy it’s correct.
^ = start of string ”^”
(?=.*\d) = must contain “?=” any set of characters “.*” but must include a digit “\d”.
(?=.*[A-Za-z]) = must contain “?=” any set of characters “.*” but must include an insensitive case letter.
.{6-12}$ = must contain any set of characters “.” but must have between 6-12 characters and end of string “$”.
|^ = or “|” start of string “^”
(?=.*[A-Za-z]) = must contain “?=” any set of characters “.*” but must include an insensitive case letter.
(?=.*[!#$%&'\(\)\*\+-\.:;<=>\?#\[\\\]\^_`\{\|\}~0x0022]|.*\s) = must contain “?=” any set of characters “.*” but must include at least special character we have defined or a space ”|.*\s)”. “0x0022” is Unicode for single quote “ character.
.{6,12}$ = set of characters “.” must be between 6 – 12 and this is the end of the string “$”
It's quite long winded, seems to be doing the job but I want to know if there is simpler methods to write this sort of regex and I want to know how I can shorten it if its possible?
Thanks in Advanced.
Does it have to be regex? Looking at the requirements, all you need is String.Length and String.IndexOfAny().
First, good job at providing comments for your regex. However, there is a much better way. Simply write your regex from the get-go in free-spacing mode with lots of comments. This way you can document your regex right in the source code (and provide indentation to improve readability when there are lots of parentheses). Here is how I would write your original regex in C# code:
if (Regex.IsMatch(usernameString,
#"# Validate username having a digit and/or special char.
^ # Either... Anchor to start of string.
(?=.*\d) # Assert there is a digit AND
(?=.*[A-Za-z]) # assert there is an alpha.
.{6-12} # Match any name with length from 6 to 12.
$ # Anchor to end of string.
| ^ # Or... Anchor to start of string
(?=.*[A-Za-z]) # Assert there is an alpha AND
(?=.* # assert there is either a special char
[!#$%&'\(\)\*\+-\.:;<=>\?#\[\\\]\^_`\{\|\}~\x22]
| .*\s # or a space char.
) # End specialchar-or-space assertion.
.{6-12} # Match any name with length from 6 to 12.
$ # Anchor to end of string.
", RegexOptions.IgnorePatternWhitespace)) {
// Valid username.
} else {
// Invalid username.
}
The code snippet above uses the preferable #"..." string syntax which simplifies the escaping of metacharacters. This original regex erroneously separates the two numbers of the curly brace quantifier using a dash, i.e. .{6-12}. The correct syntax is to separate these numbers with a comma, i.e. .*{6,12}. (Maybe .NET allows using the .{6-12} syntax?) I've also changed the 0x0022 (the " double quote char) to \x22.
That said, yes the original regex can be improved a bit:
if (Regex.IsMatch(usernameString,
#"# Validate username having a digit and/or special char.
^ # Anchor to start of string.
(?=.*?[A-Za-z]) # Assert there is an alpha.
(?: # Group for assertion alternatives.
(?=.*?\d) # Either assert there is a digit
| # or assert there is a special char
(?=.*?[!#$%&'()*+-.:;<=>?#[\\\]^_`{|}~\x22\s]) # or space.
) # End group of assertion alternatives.
.{6,12} # Match any name with length from 6 to 12.
$ # Anchor to end of string.
", RegexOptions.IgnorePatternWhitespace)) {
// Valid username.
} else {
// Invalid username.
}
This regex eliminates the global alternative and instead uses a non-capture group for the "digit or specialchar" assertion alternatives. Also, you can eliminate the non-capture group for the "special char or whitespace" alternatives by simply adding the \s to the list of special chars. I've also added a lazy modifier to the dot-stars in the assertions, i.e. .*? - (this may make the regex match a bit faster.) A bunch of unnecessary escapes were removed from the specialchar character class.
But as Stema cleverly pointed out, you can combine the digit and special char to simplify this even further:
if (Regex.IsMatch(usernameString,
#"# Validate username having a digit and/or special char.
^ # Anchor to start of string
(?=.*?[A-Za-z]) # Assert there is an alpha.
# Assert there is a special char, space
(?=.*?[!#$%&'()*+-.:;<=>?#[\\\]^_`{|}~\x22\s\d]) # or digit.
.{6,12} # Match any name with length from 6 to 12.
$ # Anchor to end of string.
", RegexOptions.IgnorePatternWhitespace)) {
// Valid username.
} else {
// Invalid username.
}
Other than that, there is really nothing wrong with your original regex with regard to accuracy. However, logically, this formula allows a username to end with whitespace which is probably not a good idea. I would also explicitly specify a whitelist of allowable chars in the name rather than using the overly permissive "." dot.
I am not sure if it makes sense what you are doing, but to achieve that, your regex can be simpler
^(?=.*[A-Za-z])(?=.*[\d\s!#$%&'\(\)\*\+-\.:;<=>\?#\[\\\]\^_`\{\|\}~0x0022]).{6,12}$
Why using alternatives? Just Add \d and \s to the character class.

Categories

Resources