Regex for my password validation - c#

I need a regular expression for my password format. It must ensure that password only contains letters a-z, digits 0-9 and special characters: .##$%&.
I am using .NET C# programming language.
This is my code:
Regex userAndPassPattern = new Regex("^[a-z0-9.##$%&]$");
if (!userAndPassPattern.IsMatch(username) || !userAndPassPattern.IsMatch(password))
return false;
The problem is that I always get back false.

!A || !B is logically equivalent to !(A && B)
So you could write better
!(userAndPassPattern.IsMatch(username) && userAndPassPattern.IsMatch(password))
Then you have a special character $ in you character class, maybe you need to mask it \$
I'm not quite sure about this, because in a character class it is not a special character. Maybe it depends on the RegEx engine in use. If you mask the $ it should do no harm ([a-z0-9.##\$%&])
Then you have just a single character to match. You need a quantifier
[a-z0-9.##$%&] means one single character out of the given, will match aor b or 0 but not ab
[a-z0-9.##$%&]+ many characters out of the given, from 1 to endless appearances, will match a, b, and ab and ba etc.
edit
This is what you want
Regex userAndPassPattern = new Regex("^[a-z0-9\.##\$%&]+$");
if (!(userAndPassPattern.IsMatch(username) && userAndPassPattern.IsMatch(password))) {
return false;
}

You forgot to add the '+' for matching one or more times:
Regex userAndPassPattern = new Regex("^[a-z0-9.##$%&]+$");

This code Regex userAndPassPattern = new Regex("^[a-z0-9.##$%&]$"); will only match a username or password that is a single character long.
You are looking for something like this Regex userAndPassPattern = new Regex("^[a-z0-9.##$%&]+$"); which will match one or more of the characters in your class. The + symbol tells it to match one or more of the previous atom (which in this case is the character class you specified in the square brackets)
Also, if you did not mean to constrain the match to lowercase characters, you should add 'A-Z' to the character class Regex userAndPassPattern = new Regex("^[A-Za-z0-9.##$%&]$");
You might also want to implement a minimum length restriction which can be accomplished by replacing the + with the {n,} construct, where n is the minimum length you want to match. For example:
this would match a minimum of 6 characters
Regex userAndPassPattern = new Regex("^[a-z0-9.##$%&]{6,}$");
this would match a minimum of 6 and a maximum of 12
Regex userAndPassPattern = new Regex("^[a-z0-9.##$%&]{6,12}$");

You have two problems. First . and $ need to be escaped. Second you are matching only 1 character. Add a + before the last $:
^[a-z0-9\.##\$%&]+$
Edit: Another suggestion, if you have a minimum/maximum length you can replace the + with, for example, {6,16} or whatever you think is appropriate. This will match strings that are 6 to 16 character inclusive and reject any shorter or longer strings. If you don't care about an upper limit, you could use {6,}.

Have you tried using a verbatim string literal when you're using regex escape sequences?
Regex userAndPassPattern = new Regex(#"^[a-z0-9##\$%&]+$");
if (!userAndPassPattern.IsMatch(username) || !userAndPassPattern.IsMatch(password))
return false;
Your pattern only allows a single character set you probably want a repetition operator like * + or {10,}.
Your character set includes . which matches any character, defeating the object of the character class. If you wanted to match "." then you need to escape it with \.

Related

Regex Numbers with 0 or 1 - follow by numbers

I'm trying to match this string, but I'm not getting to work. The string can only have either numbers or numbers with 1 dash follow by another set of numbers.
My Regex Formula:
^([0-9]*|[0-9]*\-{1}[0-9]*)$
EX:
This Pass
123
This pass
123-123
This should fail, but it's passing
123-
This should be the simplest and most efficient way of doing it:
^\d+(?:-\d+)?$
^[0-9]+(?:-[0-9]+)?$*
\d is a character set available in most regex flavors that represents [0-9]. It's a more concise way of matching numerals, but if you prefer [0-9] you can just use that instead.
Note that your original pattern and the patterns offered by others as answers here included the quantifier {1} after the hyphen. This should be avoided, as it's always redundant. A single character without a quantifier is equivalent to the same character followed by {1}.
*Edit: Wiktor brought up something I wasn't aware of. In certain regex flavors, \d includes all unicode digits rather than just the numerals 0 through 9. If this is an issue, you can just use the pattern ^[0-9]+(?:-[0-9]+)?$
You're very close!
The * quantifier matches 0 or more digits.
What you're looking for is the + quantifier which matches 1 or more digits.
Modifying your example:
^([0-9]*|[0-9]+\-{1}[0-9]+)$
Will match either nothing, a single number, or a number-number
You need to understand what the different parts of your regular expression are doing. The * symbolizes zero or any number of some symbol, in your case a number.
If you want at least one number after the dash use + instead of the star.
^([0-9]*|[0-9]*\-{1}[0-9]+)$
^[0-9]+(-[0-9]+)*$
^[0-9]+ starts with one or more numbers
(-[0-9]+)* zero or one occurance of a dash followed by a number with length of 1 or more
For the fun here are some regex-free answers. I find them easier to read.
If -123 and 123--123 are not allowed:
s.Split('-').All(x => x != string.Empty && x.All(char.IsDigit));
Foreach element between -, we check that this element is not empty and made of number only.
If -123 and 123--123 are allowed:
!s.EndsWith("-") && s.All(c => c == '-' || char.IsDigit(c));
Check that a string s does not end with - and that s is made of - and numbers only.
Try it online!
Note that char.IsDigit will allow ๔๕๖๗๘๙໐໑-௫௬௭௮. If you don't want to match this replace char.IsDigit() with IsDigit():
public static bool IsDigit(char c) => c >= '0' && c <= '9';

Regular expression only one character and 7 numbers

i want regex match only one char in any position of word and 7 numbers
match example:
1111111q
2222222q
111e1111
11e11111
i do this pattern but not working in all patterns:
[A-Za-z][0-9]{7}
Regular expressions match patterns. In your case, it would seem that the letter can be at any point in your string, which would mean that you would have a multitude of patterns which would need to be taken into consideration.
I think that for this case, you should not use regular expressions for simplicity's sake. I would recommend you take a look at the Char.isDigit(Char c) and Char.isLetter(Char c) methods and use counters to see that the string is in the format you are after.
there are readily available methods in C# for checking the conditions you want. I would use Regex if there is no parser or simple c# solution.
I would do like below
var str = "1111111u";
var isValid = str.Length ==8 &&
str.Where(char.IsDigit).Count() ==7 &&
str.Where(char.IsLetter).Count() ==1;
It is not that difficult in regex:
If the complete string has to match just use:
^(?=.{8}$)\d*[a-zA-Z]\d*$
See it here on regexr.
If this is a word in a larger text use:
\b(?=[a-z0-9]{8}\b)\d*[a-z]\d*\b
See it here on Regexr
\d*[a-z]\d* matches any amount of digits, followed by one letter, then again any amount of digits.
(?=[a-z0-9]{8} is a positive lookahead assertion, this ensures the length of 8 in total.
Important here is the use of anchors or word boundaries to avoid partial wrong matches.
If you really want to match any letter then use the Unicode property \p{L} instead of the character class:
^(?=.{8}$)\d*\p{L}\d*$
I can only come up with a "brute force" regex method:
foundMatch = Regex.IsMatch(subjectString,
#"\b
(?:[a-z]\d{7}|
\d[a-z]\d{6}|
\d{2}[a-z]\d{5}|
\d{3}[a-z]\d{4}|
\d{4}[a-z]\d{3}|
\d{5}[a-z]\d{2}|
\d{6}[a-z]\d{1}|
\d{7}[a-z])
\b",
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
Note the word boundary anchors, which you should remove if this pattern is part of a longer string.
Also note the IgnoreCase option, which you can remove if all letters will be lower case.
Edit: See #stema Answer -- much more concise regex
This will match what you want:
(\d{1}\w\d{6}|\d{2}\w\d{5}|\d{3}\w\d{4}|\d{4}\w\d{3}|\d{5}\w\d{2}|\d{6}\w\d{1}|\d{7}\w)
I generated it like this, in powershell:
$n = 6;
for ($i = 1; $i -le 6; $i++) {
write-host "\d{"$i"}\w\d{"$n"}"
$n--
}
Your example will only work when the character is the first character in the string.
The problem you've got is that you need a total of 7 digits, and absolutely only one character potentially within those 7 digits. This is not something that's possible with regular expressions as defined in theory, because you have to have a link between the two groups of digits to see how many are in the other group and regexes can't carry that kind of context around with them.
I was wondering if it was possible using a lookahead assertion to ensure there's only one letter, but the best I can do is ensuring there's no instance of two letters in a row, which doesn't cover all possible invalid cases. Thus I think you're going to have to find another method, as npinti suggested. So something like:
public static bool Match(string s) {
return (s.Length == 8) &&
(s.Where(Char.IsDigit).Count() == 7) &&
(s.Where(Char.IsLetter).Count() == 1);
}
But I haven't tested that.
just use this if you want one letter and 7 digit
"[A-Za-z]{1}[0-9]{7}|[0-9]{7}[A-Za-z]{1}|[0-9]{1}[A-Za-z]{1}[0-9]{6}[0-9]{1}|[0-9]{2}[A-Za-z]{1}[0-9]{5}|[0-9]{3}[A-Za-z]{1}[0-9]{4}|[0-9]{4}[A-Za-z]{1}[0-9]{3}|[0-9]{5}[A-Za-z]{1}[0-9]{2}"
and here a code snippet how you can iterate through your result
string st = "1111111q 2222222q 111e1111 11e11111";
string pattS = #"[A-Za-z]{1}[0-9]{7}|[0-9]{7}[A-Za-z]{1}|[0-9]{1}[A-Za-z]{1}[0-9]{6}[0-9]{1}|[0-9]{2}[A-Za-z]{1}[0-9]{5}|[0-9]{3}[A-Za-z]{1}[0-9]{4}|[0-9]{4}[A-Za-z]{1}[0-9]{3}|[0-9]{5}[A-Za-z]{1}[0-9]{2}";
Regex regex = new Regex(pattS);
var res = regex.Matches(st);
foreach (var re in res)
{
}
check here on rubular it covers all examples you provide
You can use this pattern:
^([0-9])(?:\1|[a-z](?!.*[a-z])){7}|[a-z]([0-9])\2{6}$
With Regex, you can do it in two steps. First you can remove the character, in whatever position it is:
string input = "111a1111";
Regex rgx = new Regex(#"[a-zA-Z]");
string output=rgx.Replace(input,"",1); // remove only one character
// output = "1111111"
then you can match with [0-9]{7} (if you don't want all digits to be the same)
or with ^(\d)\1{6}$ (if you want 7 occurrences of the same digit)

Regex to match all alphanumeric and certain special characters?

I am trying to get a regex to work that will allow all alphanumeric characters (both caps and non caps as well as numbers) but also allow spaces, forward slash (/), dash (-) and plus (+)?
I have been playing with a refiddle: http://refiddle.com/gqr but so far no success, anyone any ideas?
I'm not sure if it makes any difference but I am trying to do this in c#?
If you want to allow only those, you will also need the use of the anchors ^ and $.
^[a-zA-Z0-9_\s\+\-\/]+$
^ ^^
This is your regex and I added characters as indicated from the second line. Don't forget the + or * near the end to allow for more than 1 character (0 or more in the case of *), otherwise the regex will try to match only one character, even with .Matches.
You can also replace the whole class [A-Za-z0-9_] by one \w, like so:
^[\w\s\+\-\/]+$
EDIT:
You can actually avoid some escaping and avoid one last escaping with a careful placement (i.e. ensure the - is either at the beginning or at the end):
^[\w\s+/-]+$
Your regex would look something like:
/[\w\d\/\-\+ ]+/g
That's all letters, digits, and / - + and spaces (but not any other whitespace characters)
The + at the end means that at least 1 character is required. Change it to a * if you want to allow an empty string.
This code does that:
var input = "Test if / this+-works&sec0nd 2 part*3rd part";
var matches = Regex.Matches(input, #"([0-9a-zA-Z /+-]+)");
foreach (Match m in matches) if (m.Success) Console.WriteLine(m.Value);
And output will have 3 result lines:
Test if / this+-works
sec0nd 2 part
3rd---part (I showed spaces with - here)

Regular Expression: single word

I want to check in a C# program, if a user input is a single word. The word my only have characters A-Z and a-z. No spaces or other characters.
I try [A-Za-z]* , but this doesn't work. What is wrong with this expression?
Regex regex = new Regex("[A-Za-z]*");
if (!regex.IsMatch(userinput);)
{
...
}
Can you recomend website with a comprensiv list of regex examples?!
It probably works, but you aren't anchoring the regular expression. You need to use ^ and $ to anchor the expression to the beginning and end of the string, respectively:
Regex regex = new Regex("^[A-Za-z]+$");
I've also changed * to + because * will match 0 or more times while + will match 1 or more times.
You should add anchors for start and end of string: ^[A-Za-z]+$
Regarding the question of regex examples have a look at http://regexlib.com/.
For the regex, have a look at the special characters ^ and $, which represent starting and ending of string. This site can come in handy when constructing regexes in the future.
The asterisk character in regex specifies "zero or more of the preceding character class".
This explains why your expression is failing, because it will succeed if the string contains zero or more letters.
What you probably intended was to have one or more letters, in which case you should use the plus sign instead of the asterisk.
Having made that change, now it will fail if you enter a string that doesn't contain any letters, as you intended.
However, this still won't work for you entirely, because it will allow other characters in the string. If you want to restrict it to only letters, and nothing else, then you need to provide the start and end anchors (^ and $) in your regex to make the expression check that the 'one or more letters' is attached to the start and end of the string.
^[a-zA-Z]+$
This should work as intended.
Hope that helps.
For more information on regex, I recommend http://www.regular-expressions.info/reference.html as a good reference site.
I don't know what the C#'s regex syntax is, but try [A-Za-z]+.
Try ^[A-Za-z]+$ If you don't include the ^$ it will match on any part of the string that has a alpha characters in it.
I know the question is only about strictly alphabetic input, but here's an interesting way of solving this which does not break on accented letters and other such special characters.
The regex "^\b.+?\b" will match the first word on the start of a string, but only if the string actually starts with a valid word character. Using that, you can simply check if A) the string matches, and B) the length of the matched string equals your full string's length:
public Boolean IsSingleWord(String userInput)
{
Regex firstWordRegex = new Regex("^\\b.+?\\b");
Match firstWordMatch = firstWordRegex.Match(userInput);
return firstWordMatch.Success && firstWordMatch.Length == userInput.Length;
}
The other persons have wrote how to resolve the problem you know. Now I'll speak about the problem you perhaps don't know: diacritics :-) Your solution doesn't support àèéìòù and many other letters. A correct solution would be:
^(\p{L}\p{M}*)+$
where \p{L} is any letter plus \p{M}* that is 0 or more diacritic marks (in unicode diacritics can be "separated" from base letters, so you can have something like a + ` = à or you can have precomposed characters like the standard à)
if you just need the characters a-zA-Z you could simply iterate over the characters and compare the single characters if they are inside your range
for example:
for each character c: ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')
This could increase your performance

Regular expression to allow only some characters in .net

I was just working on some validation and was stuck up on this though :( I want a text which contains only [a-z][A-Z][0-9][_] .
It should accept any of the above characters any number of times in any order. All other characters marks the text as invalid.
I tried this but it is not working !!
{
......
Regex strPattern = new Regex("[0-9]*[A-Z]*[a-z]*[_]*");
if (!strPattern.IsMatch(val))
{
return false;
}
return true
}
You want this:
Regex strPattern = new Regex("^[0-9A-Za-z_]*$");
Your expression does not work because:
It will accept any number of digits, followed by any number of uppercase letters, followed by any number of lowercase letters, followed by any number of underscores. For example, an underscore followed by a number would not match.
Your pattern is not anchored using the ^ and $ characters. This means that every string will match, because every string contains zero or more of the specified characters. (For example, the string "!##$" contains zero numbers, etc.!) Anchoring the expression to the start and end of the string means that the entire string much match the entire expression or the match will fail.
This pattern will still accept a zero-length string as valid. If you would like to enforce that the string be at least one character, change the * near the end of the expression to +. (* means "0 or more of the previous token" while + means "1 or more of the previous token.")
Try this:
new Regex("[0-9A-Za-z_]*");

Categories