I have a requirement for password rules. Following are the rules.
The password must follow the following guidelines:
Be at least eight characters long
Contain 3 of these 4 options: lower case letter, upper case letter, number, or special character
When user specifies a password that does not meet the above rules, return message stating:
Password must be at least 8 characters long and contain 3 of the 4 following options:
Lower case letter (a-z)
Upper case letter (A-Z)
Number (0-9)
Special character (!##$%^&')
Please help me to get a regex expression to handle above conditions.
i appreciate all your help. following is the solution for my requirement
if(password.matches("^(?=.*[0-9]).{1,}$")){
validCount++;
}
if(password.matches("^(?=.*[a-z]).{1,}$")){
validCount++;
}
if(password.matches("^(?=.*[A-Z]).{1,}$")){
validCount++;
}
if(password.matches("^(?=.*[##$%^&+=]).{1,}$")){
validCount++;
}
return validCount >= 3 ? true : false;
Thanks,
Ramki
This is, if you want an elegant regex, as close as you can get
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!##$%^&'])[^ ]{8,}$
The basic idea is to use a technique called "positive lookahead" :
(?=.*PutHereWhatYouWantToAllow)
Your extra requirement 3 out of 4 is not easy to solve with regexes cause you cannot make them count basically.
You could write out the necessary permutations of the above regex (tell me if it doesn't make sense) but that would make a very long regex.
What you could do is write out the permutations in code so that the regex stays maintainable since you are not repeating the patterns literally.
I'll have a shot if I you tell me your language (C#?) cause it's a good challenge.
Update 1
Here is the regex that will match at least 3 of your requirements (4 is also allowed), just for the challenge of it. Don't use this in production but loop in the language with individual regexes as mentioned in the comments.
^((?=.[a-z].[A-Z].[\d])|(?=.[a-z].[\d].[A-Z])|(?=.[A-Z].[a-z].[\d])|(?=.[A-Z].[\d].[a-z])|(?=.[\d].[a-z].[A-Z])|(?=.[\d].[A-Z].[a-z])|(?=.[a-z].[A-Z].[!##$%^&'])|(?=.[a-z].[!##$%^&'].[A-Z])|(?=.[A-Z].[a-z].[!##$%^&'])|(?=.[A-Z].[!##$%^&'].[a-z])|(?=.[!##$%^&'].[a-z].[A-Z])|(?=.[!##$%^&'].[A-Z].[a-z])|(?=.[a-z].[\d].[!##$%^&'])|(?=.[a-z].[!##$%^&'].[\d])|(?=.[\d].[a-z].[!##$%^&'])|(?=.[\d].[!##$%^&'].[a-z])|(?=.[!##$%^&'].[a-z].[\d])|(?=.[!##$%^&'].[\d].[a-z])|(?=.[A-Z].[\d].[!##$%^&'])|(?=.[A-Z].[!##$%^&'].[\d])|(?=.[\d].[A-Z].[!##$%^&'])|(?=.[\d].[!##$%^&'].[A-Z])|(?=.[!##$%^&'].[A-Z].[\d])|(?=.[!##$%^&'].[\d].[A-Z]))[^ ]{8,}$
Update 2
This is the approach to take in java
From the comments I read that you are testing like the following
lowercase "^[a-z]*$";
uppercase "^[A-Z]*$";
digits="^[0-9]*$";
I don't think you are on the right track here. The lowercase will only report success if all characters are lowercase, and not just one. Same remark for the rest.
These are the 4 individual regexes of which at least 3 should report a match
[a-z]
[A-Z]
\d
[!##$%^&']
Here is the test that the password should not contain a space
^[^ ]*$
The test for at least 8 characters
.{8,}
So I split the requirements and not combine them. This should make for more readable code especially if one starts with regexes.
Here's how I would do it:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidatePassword
{
public static void main (String[] args)
{
String pw = "abaslkA3FLKJ";
// create an array with 4 regex patterns
Pattern [] patternArray = {
Pattern.compile("[a-z]"),
Pattern.compile("[A-Z]"),
Pattern.compile("[0-9]"),
Pattern.compile("[&%$#]")
};
int matchCount = 0;
// iterate over the patterns looking for matches
for (Pattern thisPattern : patternArray) {
Matcher theMatcher = thisPattern.matcher(pw);
if (theMatcher.find()) {
matchCount ++;
}
}
if (matchCount >= 3) {
System.out.println("Success");
}
else {
System.out.println("Failure: only " + matchCount + " matches");
}
}
}
I only added a few special characters to the 4th pattern... You'll have to modify it for your needs. You may need to escape certain characters with a backslash. You may also want to add other constraints like checking for no spaces. I'll leave that up to you.
Related
I want to write a regular expression that matches all 9-letter words in a word list that contain only one vowel; for example, "strengths".
The best I've achieved is:
^(([^aeiou]{8}[aeiou])|
([^aeiou]{7}[aeiou][^aeiou]{1})|
([^aeiou]{6}[aeiou][^aeiou]{2})|
([^aeiou]{5}[aeiou][^aeiou]{3})|
([^aeiou]{4}[aeiou][^aeiou]{4})|
([^aeiou]{3}[aeiou][^aeiou]{5})|
([^aeiou]{2}[aeiou][^aeiou]{6})|
([^aeiou]{1}[aeiou][^aeiou]{7})|
([aeiou][^aeiou]{8}))$
(linebreaks added for readability). This works, but is there a way to do it with a more general pattern such as:
^[^aeiou]*[aeiou][^aeiou]*$
by adding a "fail if length is not 9" condition in some way?
Use a lookahead to limit the length and accept only letters:
^(?=[a-z]{9}$)[^aeiou]*[aeiou][^aeiou]*$
You may use
^(?=.{9}$)[b-df-hj-np-tv-z]*[aeiou][b-df-hj-np-tv-z]*$
See the regex demo. Add a case insensitive flag to also match uppercase letters.
*Details
^ - start of a string
(?=.{9}$) - a *positive lookahead that makes sure the string contains any 9 chars (else, fail the match)
[b-df-hj-np-tv-z]* - 0+ consonants
[aeiou] - a vowel
[b-df-hj-np-tv-z]* - 0+ consonants
$ - end of string.
adding a "fail if length is not 9" condition in some way?"
The best way is to not check the string length using a regex.
Use the functionality provided by the language you use to check the string length then use a regex to check that it contains only the accepted characters and it includes one wovel.
A simple example in JavaScript (rewriting it in any other language is an easy task):
var input = 'some input string';
if (input.length == 9 && input.match(/[aeiou]/)) {
console.log('Valid input (length is 9 and contains at least one wovel)');
} else {
console.log('Invalid input');
}
I need regex with following conditions
It should accept maximum of 5 digits then upto 3 decimal places
it can be negative
it can be zero
it can be only numbers (max. upto 5 digit place)
it can be null
I have tried following but its not, its not fulfilling all conditions
#"^([\-\+]?)\d{0,5}(.[0-9]{1,3})?)$"
E.g. maximum value can hold is from -99999.999 to 99999.999
Use this regex:
^[-+]?\d{0,5}(\.[0-9]{1,3})?$
I only made two changes here. First, you don't need to escape any characters inside a character class normally, except for opening and closing brackets, or possibly backslash itself. Hence, we can use [-+] to capture an initial plus or minus. Second, you need to escape the dot in your regex, to tell the engine that you want to match a literal dot.
However, I would probably phrase this regex as follows:
^[-+]?\d{1,5}(\.[0-9]{1,3})?$
This will match one to five digits, followed by an optional decimal point, followed by one to three digits.
Note that we want to capture things like:
0.123
But not
.123
i.e. we don't want to capture a leading decimal point should it not be prefixed by at least one number.
Demo here:
Regex101
I assume you're doing this in C# given the notation. Here's a little code you can use to test your expression, with two corrections:
You have to escape the dot, otherwise it means "any character". So, \. instead of .
There was an extraneous close parenthesis that prevented the expression from compiling
C#:
var expr = #"^([\-\+]?)\d{0,5}(\.[0-9]{1,3})?$";
var re = new Regex(expr);
string[] samples = {
"",
"0",
"1.1",
"1.12",
"1.123",
"12.3",
"12.34",
"12.345",
"123.4",
"12345.123",
".1",
".1234"
};
foreach(var s in samples) {
Console.WriteLine("Testing [{0}]: {1}", s, re.IsMatch(s) ? "PASS" : "FAIL");
}
Results:
Testing []: PASS
Testing [0]: PASS
Testing [1.1]: PASS
Testing [1.12]: PASS
Testing [1.123]: PASS
Testing [12.3]: PASS
Testing [12.34]: PASS
Testing [12.345]: PASS
Testing [123.4]: PASS
Testing [12345.123]: PASS
Testing [.1]: PASS
Testing [.1234]: FAIL
It should accept maximum of 5 digits
[0-9]{1,5}
then upto 3 decimal places
[0-9]{1,5}(\.[0-9]{1,3})?
it can be negative
[-]?[0-9]{1,5}(\.[0-9]{1,3})?
it can be zero
Already covered.
it can be only numbers (max. upto 5 digit place)
Already covered. 'Up to 5 digit place' contradicts your first rule, which allows 5.3.
it can be null
Not covered. I strongly suggest you remove this requirement. Even if you mean 'empty', as I sincerely hope you do, you should detect that case separately and beforehand, as you will certainly have to handle it differently.
Your regular expression contains ^ and $. I don't know why. There is nothing about start of line or end of line in the rules you specified. It also allows a leading +, which again isn't specified in your rules.
I am new in regular expression.
I want to validate my password which must contains any three from below:
One digit
one Lower letter
one Upper case Letter
One special letter from this set of characters
.~^;:?=##${}|_()*,-
If any user enters One digit, One lower case letter, One Upper case letter and Special letter not from above group i.e 1234S%n&, expression should return false.
I have tried below expression :
(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).*$|(?=.*\d)(?=.*[A-Z])(?=.*[.~^;:?=##${}|_()*,-])(?!.*[+&%<>]).*$|(?=.*\d)(?=.*[a-z])(?=.*[.~^;:?=##${}|_()*,-])(?!.*[&+%<>]).*$|(?=.*[A-Z])(?=.*[a-z])(?=.*[.~^;:?=##${}|_()*,-])(?!.*[&+%<>]).*$
Please help me to solve my confusion
Match "at least n criteria, any of the following" is not very easy to do in a single regex.
I would recommend against it, and doing it in multiple steps (quick&dirty pseudo code):
password = "1234S%x"
i = 0
// only allowed characters are in the string
char_validated = password.find("^[a-zA-Z0-9.~^;:?=##${}|_()*,-]+$")
if password.find("[0-9]") then i++ // check for at least one digit
if password.find("[a-z]") then i++ // check for at least one lowercase
if password.find("[A-Z]") then i++ // check for at least one uppercase
if password.find("[.~^;:?=##${}|_()*,-]") then i++ // check for at least one special
if (i>=3 && char_validated) then ok
If you really need to do it in one regex, you could use your refactored not-easy-on-the-eye regex:
^(?:(?=.*\d)(?:(?=.*[A-Z])(?=.*[a-z])|(?=.*[A-Z])(?=.*[.~^;:?=##${}|_()*,-])|(?=.*[a-z])(?=.*[.~^;:?=##${}|_()*,-]))|(?=.*[A-Z])(?=.*[a-z])(?=.*[.~^;:?=##${}|_()*,-]))[a-zA-Z0-9.~^;:?=##${}|_()*,-]+$
See demo here.
The idea is, instead of allowing anything after checking with lookaheads, to force the allowed characters with [a-zA-Z0-9.~^;:?=##${}|_()*,-]
I have been searching for regular expression which accepts at least two digits and one special character and minimum password length is 8. So far I have done the following: [0-9a-zA-Z!##$%0-9]*[!##$%0-9]+[0-9a-zA-Z!##$%0-9]*
Something like this should do the trick.
^(?=(.*\d){2})(?=.*[a-zA-Z])(?=.*[!##$%])[0-9a-zA-Z!##$%]{8,}
(?=(.*\d){2}) - uses lookahead (?=) and says the password must contain at least 2 digits
(?=.*[a-zA-Z]) - uses lookahead and says the password must contain an alpha
(?=.*[!##$%]) - uses lookahead and says the password must contain 1 or more special characters which are defined
[0-9a-zA-Z!##$%] - dictates the allowed characters
{8,} - says the password must be at least 8 characters long
It might need a little tweaking e.g. specifying exactly which special characters you need but it should do the trick.
There is no reason, whatsoever, to implement all rules in a single regex.
Consider doing it like thus:
Pattern[] pwdrules = new Pattern[] {
Pattern.compile("........"), // at least 8 chars
Pattern.compile("\d.*\d"), // 2 digits
Pattern.compile("[-!"ยง$%&/()=?+*~#'_:.,;]") // 1 special char
}
String password = ......;
boolean passed = true;
for (Pattern p : pwdrules) {
Matcher m = p.matcher(password);
if (m.find()) continue;
System.err.println("Rule " + p + " violated.");
passed = false;
}
if (passed) { .. ok case.. }
else { .. not ok case ... }
This has the added benefit that passwort rules can be added, removed or changed without effort. They can even reside in some ressource file.
In addition, it is just more readable.
Try this one:
^(?=.*\d{2,})(?=.*[$-/:-?{-~!"^_`\[\]]{1,})(?=.*\w).{8,}$
Here's how it works shortly:
(?=.*\d{2,}) this part saying except at least 2 digits
(?=.*[$-/:-?{-~!"^_[]]{1,})` these are special characters, at least 1
(?=.*\w) and rest are any letters (equals to [A-Za-z0-9_])
.{8,}$ this one says at least 8 characters including all previous rules.
Below is map for current regexp (made with help of Regexper)
UPD
Regexp should look like this ^(?=(.*\d){2,})(?=.*[$-\/:-?{-~!"^_'\[\]]{1,})(?=.*\w).{8,}$
Check out comments for more details.
Try this regex. It uses lookahead to verified there is a least two digits and one of the special character listed by you.
^(?=.*?[0-9].*?[0-9])(?=.*[!##$%])[0-9a-zA-Z!##$%0-9]{8,}$
EXPLANATION
^ #Match start of line.
(?=.*?[0-9].*?[0-9]) #Look ahead and see if you can find at least two digits. Expression will fail if not.
(?=.*[!##$%]) #Look ahead and see if you can find at least one of the character in bracket []. Expression will fail if not.
[0-9a-zA-Z!##$%0-9]{8,} #Match at least 8 of the characters inside bracket [] to be successful.
$ # Match end of line.
Regular expressions define a structure on the string you're trying to match. Unless you define a spatial structure on your regex (e.g. at least two digits followed by a special char, followed by ...) you cannot use a regex to validate your string.
Try this : ^.*(?=.{8,15})(?=.*\d)(?=.*\d)[a-zA-Z0-9!##$%]+$
Please read below link for making password regular expression policy:-
Regex expression for password rules
This question already has answers here:
Regexp Java for password validation
(17 answers)
Closed 8 years ago.
Working on a project where it requires me to have a password field using pattern attribute.
Not really done a lot of regex stuff and was wondering whether someone could help out.
The requirements for the field are as follows:
Can't contain the word "password"
Must be 8-12 in length
Must have 1 upper case
Must have 1 lower case
Must have 1 digit
Now, so far I have the following:
[^(password)].(?=.*[0-9])?=.*[a-zA-Z]).{8,12}
This doesn't work. We can get it so everything else works, apart from the password string being matched.
Thanks in advance,
Andy
EDIT: the method we've used now (nested in comments below) is:
^(?!.*(P|p)(A|a)(S|s)(S|s)(W|w)(O|o)(R|r)(D|d)).(?=.*\d)(?=.*[a-zA-Z]).{8,12}$
Thanks for the help
Use a series of anchored look aheads for the :must contain" criteria:
^(?!.*(?i)password)(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,12}$
I've added the "ignore case" switch (?i) to the "password" requirement, so it will reject `the word no matter the case of the letters.
This regex should to the job:
^(?!.*password)(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{8,12}$
it will match:
^ // from the beginning of the input
(?!.*password) // negative lookbehind whether the text contains password
(?=.*\d+) // positive lookahead for at least one digit
(?=.*[A-Z]+) // positive lookahead for at least one uppercase letter
(?=.*[a-z]+) // positive lookahead for at least one lowercase letter
.{8,12} // length of the input is between 8 and 12 characters
$
Link to phpliveregex
Try This:
^(?!.*password)(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{8,12}$
Explanation
^ Start anchor
(?=.*[A-Z]) Ensure string has one uppercase letter
(?=.*[0-9]) Ensure string has one digits.
(?=.*[a-z]) Ensure string has one lowercase letter
{8,12} Ensure string is of length 8 - 12.
(?!.*password) Not of word password
$ End anchor.
Try this way
Public void validation()
string xxxx = "Aa1qqqqqq";
if (xxxx.ToUpper().Contains("password") || !(xxxx.Length <= 12 & xxxx.Length >= 8) || !IsMatch(xxxx, "(?=.*[A-Z])") || !IsMatch(xxxx, "(?=.*[a-z])") || !IsMatch(xxxx, "(?=.*[0-9])"))
{
throw new System.ArgumentException("Your error message here", "Password");
}
}
public bool IsMatch(string input, string pattern)
{
Match xx = Regex.Match(input, pattern);
return xx.Success;
}