Regex match 2 alpha plus 6 digits in C# - c#

I need a regex to match this pattern ( using C# )
My match must start with 2 alpha characters ( MA or CA ) and must end with either 6 or seven numeric digits; such as CA123456 or MA123456 or MA1234567
Here is what I tried:
Regex.IsMatch(StringInput, #"^[MA]{2}|^[CA]{2}\d{6,7}?"))
Unfortunately, it seems to match most anything

Try this pattern:
^[MC]A\d{6,7}$
The leading character class ([MC]) requires either an M or a C at the start of the string. Afterwards, \d{6,7} matches either 6 or 7 digits.
The issue with your pattern is the first alternative: ^[MA]{2} matches any string that starts with AA, AM, MA, or MM. It doesn't require any following digits at all. Since the regex engine can match the first alternative for a string like AA1234567 (matching the substring AA), it doesn't even attempt to find another match. This is why
it seems to match most anything.

I believe there are great usages of RegEx; in this particular case, using the built-in string functions of C# may be a better option:
Must start with either MA or CA
Must end with at least 6 digits (if there are 7, then there will be 6 digits)
Combining 1 and 2, the string must be at least 8 characters long
This would be the string version based on the above rules:
public static bool IsValid( string str )
{
if( str.Length < 8 )
{
return false;
}
if( !str.StartsWith( "CA" ) && !str.StartsWith( "MA" ) )
{
return false;
}
int result;
string end = str.Substring( str.Length - 6 );
bool isValid = int.TryParse( end, out result );
return isValid;
}

Related

Password must be minimum 8 characters including 1 uppercase letter,1 lowercase 1 special character( from: !, #, #, $, %, ?, &) [duplicate]

I want a regular expression to check that
a password must be 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])(?=.*[A-Z])(?=.*[a-z]).*$"
How I can write it for a password that must be eight characters including one uppercase letter, one special character and alphanumeric characters?
The regular expression you are after will most likely be huge and a nightmare to maintain especially for people who are not that familiar with regular expressions.
I think it would be easier to break your regex down and do it one bit at a time. It might take a bit more to do, but I am pretty sure that maintaining it and debugging it would be easier. This would also allow you to provide more directed error messages to your users (other than just Invalid Password) which should improve user experience.
From what I am seeing you are pretty fluent in regex, so I would presume that giving you the regular expressions to do what you need would be futile.
Seeing your comment, this is how I would go about it:
Must be eight characters Long: You do not need a regex for this. Using the .Length property should be enough.
Including one uppercase letter: You can use the [A-Z]+ regular expression. If the string contains at least one upper case letter, this regular expression will yield true.
One special character: You can use either the \W which will match any character which is not a letter or a number or else, you can use something like so [!##] to specify a custom list of special characters. Note though that characters such as $, ^, ( and ) are special characters in the regular expression language, so they need to be escaped like so: \$. So in short, you might use the \W.
Alphanumeric characters: Using the \w+ should match any letter and number and underscore.
Take a look at this tutorial for more information.
( # Start of group
(?=.*\d) # must contain at least one digit
(?=.*[A-Z]) # must contain at least one uppercase character
(?=.*\W) # must contain at least one special symbol
. # match anything with previous condition checking
{8,8} # length is exactly 8 characters
) # End of group
In one line:
((?=.*\d)(?=.*[A-Z])(?=.*\W).{8,8})
Edit 2019-05-28:
You need to match entire input string. So, you can enclose the regex between ^ and $ to prevent accidentally assuming partial matches as matching entire input:
^((?=.*\d)(?=.*[A-Z])(?=.*\W).{8,8})$
Sources:
Password matching expression
Password Strength Validation with Regular Expressions
So many answers.... all bad!
Regular expressions don't have an AND operator, so it's pretty hard to write a regex that matches valid passwords, when validity is defined by something AND something else AND something else...
But, regular expressions do have an OR operator, so just apply DeMorgan's theorem, and write a regex that matches invalid passwords.
anything with less than 8 characters OR anything with no numbers OR anything with no uppercase OR anything with no special characters
So:
^(.{0,7}|[^0-9]*|[^A-Z]*|[a-zA-Z0-9]*)$
If anything matches that, then it's an invalid password.
The answer is to not use a regular expression. This is sets and counting.
Regular expressions are about order.
In your life as a programmer you will asked to do many things that do not make sense. Learn to dig a level deeper. Learn when the question is wrong.
The question (if it mentioned regular expressions) is wrong.
Pseudocode (been switching between too many languages, of late):
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)
Bet you read and understood the above code almost instantly. Bet you took much longer with the regex, and are less certain it is correct. Extending the regex is risky. Extended the immediate above, much less so.
Note also the question is imprecisely phrased. Is the character set ASCII or Unicode, or ?? My guess from reading the question is that at least one lowercase character is assumed. So I think the assumed last rule should be:
return (0 < nUpper) and (0 < nLower) and (0 < nAlphanum) and (0 < nSpecial)
(Changing hats to security-focused, this is a really annoying/not useful rule.)
Learning to know when the question is wrong is massively more important than clever answers. A clever answer to the wrong question is almost always wrong.
As an example how this could be done with a readable/maintainable regex.
For a longer regex you should always use RegexOptions.IgnorePatternWhitespace to allow whitespace 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();
If you need only one upper case and special character then this should work:
#"^(?=.{8,}$)(?=[^A-Z]*[A-Z][^A-Z]*$)\w*\W\w*$"
The regular expression you was looking for is: /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*\[\]"\';:_\-<>\., =\+\/\\]).{8,}$/u.
Example and test: http://regexr.com/3fhr4
This question starts to be viral and a lot of interesting suggestion appeared.
Yes, writing by hand is difficult. So an easier solution is to use a template. Although the resulted regex may not be most optimal, it will be easier to maintain and/or change, and the user will have a better control over the result. It is possible that I missed something, so any constructive criticism will be helpful.
This links might be interesting: match at least 2 digits 2 letters in any order in a string, Regular Expression Language, Capturing groups
I'm using this template (?=(?:.*?({type})){({count})}) based on all of the regex I saw in SO. The next step is replacing the needed pattern ( number, special character ... ) and adding configuration for length.
I've made a little class for composing the regex PasswordRegexGenerator.cs
An 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", "[A-Z]" },
{ "lowercase", "[a-z]" },
{ "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 ( ) + ")";
}
}
You can use below class for validation:
public class PasswordValidator{
private Pattern pattern;
private Matcher matcher;
private static final String PASSWORD_PATTERN =
"((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{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 minimum and maximum length for the password.
Use a nonbacktracking expression to match the whole password first, if it has at least 8 characters (this way, there is no combinatorial explosion for long, but invalid passwords): (?>{8,})
Use lookbehind assertions to check for presence of all required characters (AND-conditions). (?<=...)
At least one uppercase character: (?<=\p{Lu}.*)
At least one special character (a bit ambiguous, but let's use not-word): (?<=\W.*)
At least one alphanumeric character (: (?<=\w.*)
Summed up:
(?>.{8,})(?<=\p{Lu}.*)(?<=\W.*)(?<=\w.*)
Best is not using regex for everything. Those requirements are very light. On CPU-wise string operations for checking the criteria/validation is much cheaper and faster than regex!
The one I found for a minimum of 8 characters, consist of at least 1 lowercase and 1 uppercase and 1 number and 1 symbols.
^((?=.*\d)(?=.*[A-Z])(?=.*\W).{8,})$
var regex =/^(?=.*\d)(?=.*[!##$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,64}$/;
function test() {
if(regex.test(document.getElementById("txtPassword").value)===false)
{
alert("Min 6,Max 64,At Least One Uppercase Character,One Lowercase Character,One Numeric Value And One Special Character(!##$%^&*) Required ");
}
else
{
alert("Success");
}
}
<input type="text" id="txtPassword" />
<button id="testBtn" onclick=test()>CheckPassword</button>
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/

Regex for alphanumeric, at least 1 number and special chars

I am trying to find a regex which will give me the following validation:
string should contain at least 1 digit and at least 1 special character. Does allow alphanumeric.
I tried the following but this fails:
#"^[a-zA-Z0-9##$%&*+\-_(),+':;?.,!\[\]\s\\/]+$]"
I tried "password1$" but that failed
I also tried "Password1!" but that also failed.
ideas?
UPDATE
Need the solution to work with C# - currently the suggestions posted as of Oct 22 2013 do not appear to work.
Try this:
Regex rxPassword = new Regex( #"
^ # start-of-line, followed by
[a-zA-Z0-9!##]+ # a sequence of one or more characters drawn from the set consisting of ASCII letters, digits or the punctuation characters ! # and #
(<=[0-9]) # at least one of which is a decimal digit
(<=[!##]) # at least one of which is one of the special characters
(<=[a-zA-Z]) # at least one of which is an upper- or lower-case letter
$ # followed by end-of-line
" , RegexOptions.IgnorePatternWhitespace ) ;
The construct (<=regular-expression) is a zero-width positive look-behind assertion.
Sometimes it's a lot simpler to do things one step at a time. The static constructor builds the escaped character class characters from a simple list of allowed special characters. The built-in Regex.Escape method doesn't work here.
public static class PasswordValidator {
private const string ALLOWED_SPECIAL_CHARS = #"##$%&*+_()':;?.,![]\-";
private static string ESCAPED_SPECIAL_CHARS;
static PasswordValidator() {
var escapedChars = new List<char>();
foreach (char c in ALLOWED_SPECIAL_CHARS) {
if (c == '[' || c == ']' || c == '\\' || c == '-')
escapedChars.AddRange(new[] { '\\', c });
else
escapedChars.Add(c);
}
ESCAPED_SPECIAL_CHARS = new string(escapedChars.ToArray());
}
public static bool IsValidPassword(string input) {
// Length requirement?
if (input.Length < 8) return false;
// First just check for a digit
if (!Regex.IsMatch(input, #"\d")) return false;
// Then check for special character
if (!Regex.IsMatch(input, "[" + ESCAPED_SPECIAL_CHARS + "]")) return false;
// Require a letter?
if (!Regex.IsMatch(input, "[a-zA-Z]")) return false;
// DON'T allow anything else:
if (Regex.IsMatch(input, #"[^a-zA-Z\d" + ESCAPED_SPECIAL_CHARS + "]")) return false;
return true;
}
}
This may be work, there are two possible, the digit before special char or the digit after the special char. You should use DOTALL(the dot point all char)
^((.*?[0-9].*?[##$%&*+\-_(),+':;?.,!\[\]\s\\/].*)|(.*?[##$%&*+\-_(),+':;?.,!\[\]\s\\/].*?[0-9].*))$
This worked for me:
#"(?=^[!##$%\^&*()_-+=[{]};:<>|./?a-zA-Z\d]{8,}$)(?=([!##$%\^&*()_-+=[{]};:<>|./?a-zA-Z\d]\W+){1,})(?=[^0-9][0-9])[!##$%\^&*()_-+=[{]};:<>|./?a-zA-Z\d]*$"
alphanumeric, at least 1 numeric, and special character with a min length of 8
This should do the work
(?:(?=.*[0-9]+)(?=.*[a-zA-Z]+)(?=.*[##$%&*+\-_(),+':;?.,!\[\]\s\\/]+))+
Tested with javascript, not sure about c#, may need some little adjust.
What it does is use anticipated positive lookahead to find the required elements of the password.
EDIT
Regular expression is designed to test if there are matches. Since all the patterns are lookahead, no real characters get captured and matches are empty, but if the expression "match", then the password is valid.
But, since the question is C# (sorry, i don't know c#, just improvising and adapting samples)
string input = "password1!";
string pattern = #"^(?:(?=.*[0-9]+)(?=.*[a-zA-Z]+)(?=.*[##$%&*+\-_(),+':;?.,!\[\]\s\\/]+))+.*$";
Regex rgx = new Regex(pattern, RegexOptions.None);
MatchCollection matches = rgx.Matches(input);
if (matches.Count > 0) {
Console.WriteLine("{0} ({1} matches):", input, matches.Count);
foreach (Match match in matches)
Console.WriteLine(" " + match.Value);
}
Adding start of line, and a .*$ to the end, the expression will match if the password is valid. And the match value will be the password. (i guess)

RegEx to match different substrings based on string length

I'm looking for a regular expression to match an alphanumeric string. If the string is 32 characters long, match characters 17 to 28. If the string is 34 characters long, match the last 12 characters.
RegEx Match Conditions http://s12.postimage.org/ghathiz2l/Screen_shot_2012_08_09_at_11_52_22_PM.png
I have two separate expressions to get matches for the two different conditions.
.(?<match>[0-9]{16}) and .(?<match>[0-9]{12})
In the code, I read the expressions right to left, handle the 'if' and truncate the last 4 characters of the match when the original string is 32 characters long but would like to be able to do this from a single RegEx.
EDIT
I would indeed prefer to do away with the RegEx in this case but I am not the original author of the app. The string-parsing conditions may change over time so it is simpler to maintain the RegEx in the config file than to make a new release in this instance. Plus, it's what the boss wants...
Try this:
^(.{22}(.{12}))|(.{16}(.{12}).{4})$
$1 is the entire match for the first case (34 chars long); $2 is the matched 12 chars.
$3 is the entire match for the second case (32 chars long); $4 is the matched 12 chars.
Easy!
The other, and arguably easier, way, is to look at the inbound string and assign the correct regex instance based on string length:
private static Regex rx34 = ... ;
private static Regex rx32 = ... ;
string foo( string s )
{
Regex rx ;
switch ( s.Length )
{
case 34 : rx = rx34 ; break ;
case 32 : rx = rx32 ; break ;
default : throw new ArgumentOutOfRangeException("s") ;
}
Match m = rx.Match(s) ;
if ( !m.Success ) throw new InvalidOperationException() ;
... // return the appropriate part of the string.
}
Or, why use the regex at all? This isn't a problem for a regex.
string foo( string s )
{
string s12 ;
switch (( s ?? "" ).Length)
{
case 34 : return s12 = s.Substring( 34 - 12 ) ;
case 32 : return s12 = s.Substring( 16 , 12 ) ;
default : throw new ArgumentOutOfRangeException("s");
}
return s12 ;
}
Because life is too hard to make things more difficult than they are.

Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

I want a regular expression to check that
a password must be 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])(?=.*[A-Z])(?=.*[a-z]).*$"
How I can write it for a password that must be eight characters including one uppercase letter, one special character and alphanumeric characters?
The regular expression you are after will most likely be huge and a nightmare to maintain especially for people who are not that familiar with regular expressions.
I think it would be easier to break your regex down and do it one bit at a time. It might take a bit more to do, but I am pretty sure that maintaining it and debugging it would be easier. This would also allow you to provide more directed error messages to your users (other than just Invalid Password) which should improve user experience.
From what I am seeing you are pretty fluent in regex, so I would presume that giving you the regular expressions to do what you need would be futile.
Seeing your comment, this is how I would go about it:
Must be eight characters Long: You do not need a regex for this. Using the .Length property should be enough.
Including one uppercase letter: You can use the [A-Z]+ regular expression. If the string contains at least one upper case letter, this regular expression will yield true.
One special character: You can use either the \W which will match any character which is not a letter or a number or else, you can use something like so [!##] to specify a custom list of special characters. Note though that characters such as $, ^, ( and ) are special characters in the regular expression language, so they need to be escaped like so: \$. So in short, you might use the \W.
Alphanumeric characters: Using the \w+ should match any letter and number and underscore.
Take a look at this tutorial for more information.
( # Start of group
(?=.*\d) # must contain at least one digit
(?=.*[A-Z]) # must contain at least one uppercase character
(?=.*\W) # must contain at least one special symbol
. # match anything with previous condition checking
{8,8} # length is exactly 8 characters
) # End of group
In one line:
((?=.*\d)(?=.*[A-Z])(?=.*\W).{8,8})
Edit 2019-05-28:
You need to match entire input string. So, you can enclose the regex between ^ and $ to prevent accidentally assuming partial matches as matching entire input:
^((?=.*\d)(?=.*[A-Z])(?=.*\W).{8,8})$
Sources:
Password matching expression
Password Strength Validation with Regular Expressions
So many answers.... all bad!
Regular expressions don't have an AND operator, so it's pretty hard to write a regex that matches valid passwords, when validity is defined by something AND something else AND something else...
But, regular expressions do have an OR operator, so just apply DeMorgan's theorem, and write a regex that matches invalid passwords.
anything with less than 8 characters OR anything with no numbers OR anything with no uppercase OR anything with no special characters
So:
^(.{0,7}|[^0-9]*|[^A-Z]*|[a-zA-Z0-9]*)$
If anything matches that, then it's an invalid password.
The answer is to not use a regular expression. This is sets and counting.
Regular expressions are about order.
In your life as a programmer you will asked to do many things that do not make sense. Learn to dig a level deeper. Learn when the question is wrong.
The question (if it mentioned regular expressions) is wrong.
Pseudocode (been switching between too many languages, of late):
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)
Bet you read and understood the above code almost instantly. Bet you took much longer with the regex, and are less certain it is correct. Extending the regex is risky. Extended the immediate above, much less so.
Note also the question is imprecisely phrased. Is the character set ASCII or Unicode, or ?? My guess from reading the question is that at least one lowercase character is assumed. So I think the assumed last rule should be:
return (0 < nUpper) and (0 < nLower) and (0 < nAlphanum) and (0 < nSpecial)
(Changing hats to security-focused, this is a really annoying/not useful rule.)
Learning to know when the question is wrong is massively more important than clever answers. A clever answer to the wrong question is almost always wrong.
As an example how this could be done with a readable/maintainable regex.
For a longer regex you should always use RegexOptions.IgnorePatternWhitespace to allow whitespace 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();
If you need only one upper case and special character then this should work:
#"^(?=.{8,}$)(?=[^A-Z]*[A-Z][^A-Z]*$)\w*\W\w*$"
The regular expression you was looking for is: /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*\[\]"\';:_\-<>\., =\+\/\\]).{8,}$/u.
Example and test: http://regexr.com/3fhr4
This question starts to be viral and a lot of interesting suggestion appeared.
Yes, writing by hand is difficult. So an easier solution is to use a template. Although the resulted regex may not be most optimal, it will be easier to maintain and/or change, and the user will have a better control over the result. It is possible that I missed something, so any constructive criticism will be helpful.
This links might be interesting: match at least 2 digits 2 letters in any order in a string, Regular Expression Language, Capturing groups
I'm using this template (?=(?:.*?({type})){({count})}) based on all of the regex I saw in SO. The next step is replacing the needed pattern ( number, special character ... ) and adding configuration for length.
I've made a little class for composing the regex PasswordRegexGenerator.cs
An 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", "[A-Z]" },
{ "lowercase", "[a-z]" },
{ "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 ( ) + ")";
}
}
You can use below class for validation:
public class PasswordValidator{
private Pattern pattern;
private Matcher matcher;
private static final String PASSWORD_PATTERN =
"((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{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 minimum and maximum length for the password.
Use a nonbacktracking expression to match the whole password first, if it has at least 8 characters (this way, there is no combinatorial explosion for long, but invalid passwords): (?>{8,})
Use lookbehind assertions to check for presence of all required characters (AND-conditions). (?<=...)
At least one uppercase character: (?<=\p{Lu}.*)
At least one special character (a bit ambiguous, but let's use not-word): (?<=\W.*)
At least one alphanumeric character (: (?<=\w.*)
Summed up:
(?>.{8,})(?<=\p{Lu}.*)(?<=\W.*)(?<=\w.*)
Best is not using regex for everything. Those requirements are very light. On CPU-wise string operations for checking the criteria/validation is much cheaper and faster than regex!
The one I found for a minimum of 8 characters, consist of at least 1 lowercase and 1 uppercase and 1 number and 1 symbols.
^((?=.*\d)(?=.*[A-Z])(?=.*\W).{8,})$
var regex =/^(?=.*\d)(?=.*[!##$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,64}$/;
function test() {
if(regex.test(document.getElementById("txtPassword").value)===false)
{
alert("Min 6,Max 64,At Least One Uppercase Character,One Lowercase Character,One Numeric Value And One Special Character(!##$%^&*) Required ");
}
else
{
alert("Success");
}
}
<input type="text" id="txtPassword" />
<button id="testBtn" onclick=test()>CheckPassword</button>
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/

.Net Removing all the first 0 of a string

I got the following :
01.05.03
I need to convert that to 1.5.3
The problem is I cannot only trim the 0 because if I got :
01.05.10
I need to convert that to 1.5.10
So, what's the better way to solve that problem ? Regex ? If so, any regex example doing that ?
Expanding on the answer of #FrustratedWithFormsDesigner:
string Strip0s(string s)
{
return string.Join<int>(".", from x in s.Split('.') select int.Parse(x));
}
Regex-replace
(?<=^|\.)0+
with the empty string. The regex is:
(?<= # begin positive look-behind (i.e. "a position preceded by")
^|\. # the start of the string or a literal dot †
) # end positive look-behind
0+ # one or more "0" characters
† note that not all regex flavors support variable-length look-behind, but .NET does.
If you expect this kind of input: "00.03.03" and want to to keep the leading zero in this case (like "0.3.3"), use this expression instead:
(?<=^|\.)0+(?=\d)
and again replace with the empty string.
From the comments (thanks Kobi): There is a more concise expression that does not require look-behind and is equivalent to my second suggestion:
\b0+(?=\d)
which is
\b # a word boundary (a position between a word char and a non-word char)
0+ # one or more "0" characters
(?=\d) # positive look-ahead: a position that's followed by a digit
This works because the 0 happens to be a word character, so word boundaries can be used to find the first 0 in a row. It is a more compatible expression, because many regex flavors do not support variable-length look-behind, and some (like JavaScript) no look-behind at all.
You could split the string on ., then trim the leading 0s on the results of the split, then merge them back together.
I don't know of a way to do this in a single operation, but you could write a function that hides this and makes it look like a single operation. ;)
UPDATE:
I didn't even think of the other guy's regex. Yeah, that will probably do it in a single operation.
Here's another way you could do what FrustratedWithFormsDesigner suggests:
string s = "01.05.10";
string s2 = string.Join(
".",
s.Split('.')
.Select(str => str.TrimStart('0'))
.ToArray()
);
This is almost the same as dtb's answer, but doesn't require that the substrings be valid integers (it would also work with, e.g., "000A.007.0HHIMARK").
UPDATE: If you'd want any strings consisting of all 0s in the input string to be output as a single 0, you could use this:
string s2 = string.Join(
".",
s.Split('.')
.Select(str => TrimLeadingZeros(str))
.ToArray()
);
public static string TrimLeadingZeros(string text) {
int number;
if (int.TryParse(text, out number))
return number.ToString();
else
return text.TrimStart('0');
}
Example input/output:
00.00.000A.007.0HHIMARK // input
0.0.A.7.HHIMARK // output
There's also the old-school way which probably has better performance characteristics than most other solutions mentioned. Something like:
static public string NormalizeVersionString(string versionString)
{
if(versionString == null)
throw new NullArgumentException("versionString");
bool insideNumber = false;
StringBuilder sb = new StringBuilder(versionString.Length);
foreach(char c in versionString)
{
if(c == '.')
{
sb.Append('.');
insideNumber = false;
}
else if(c >= '1' && c <= '9')
{
sb.Append(c);
insideNumber = true;
}
else if(c == '0')
{
if(insideNumber)
sb.Append('0');
}
}
return sb.ToString();
}
string s = "01.05.10";
string newS = s.Replace(".0", ".");
newS = newS.StartsWith("0") ? newS.Substring(1, newS.Length - 1) : newS;
Console.WriteLine(newS);
NOTE: You will have to thoroughly check for possible input combination.
This looks like it is a date format, if so I would use Date processing code
DateTime time = DateTime.Parse("01.02.03");
String newFormat = time.ToString("d.M.yy");
or even better
String newFormat = time.ToShortDateString();
which will respect you and your clients culture setting.
If this data is not a date then don't use this :)
I had a similar requirement to parse a string with street adresses, where some of the house numbers had leading zeroes and I needed to remove them while keeping the rest of the text intact, so I slightly edited the accepted answer to meet my requirements, maybe someone finds it useful. Basically doing the same as accepted answer, with the difference that I am checking if the string part can be parsed as an integer, and defaulting to the string value when false;
string Strip0s(string s)
{
int outputValue;
return
string.Join(" ",
from x in s.Split(new[] { ' ' })
select int.TryParse(x, out outputValue) ? outputValue.ToString() : x);
}
Input: "Islands Brygge 34 B 07 TV"
Output: "Islands Brygge 34 B 7 TV"

Categories