To test one alphanumeric string we usually use the regular expression "^[a-zA-Z0-9_]*$"
(or most preferably "^\w+$"
for C#). But this regex accepts numeric only strings or alphabet only strings, like "12345678"
or "asdfgth"
.
I need one regex which will accept only the alphanumeric strings that have at-least one alphabet and one number. That is to say by the regex "ar56ji"
will be one of the correct strings, not the previously said strings.
Thanks in advance.
For checking if a string consists only of alphanumerics using module regular expression or regex, we can call the re. match(regex, string) using the regex: "^[a-zA-Z0-9]+$". re. match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1. 1* means any number of ones.
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .
This should do it:
if (Regex.IsMatch(subjectString, @"
# Match string having one letter and one digit (min).
\A # Anchor to start of string.
(?=[^0-9]*[0-9]) # at least one number and
(?=[^A-Za-z]*[A-Za-z]) # at least one letter.
\w+ # Match string of alphanums.
\Z # Anchor to end of string.
",
RegexOptions.IgnorePatternWhitespace)) {
// Successful match
} else {
// Match attempt failed
}
EDIT 2012-08-28 Improved efficiency of lookaheads by changing the lazy dot stars to specific greedy char classes.
Try this out:
"^\w*(?=\w*\d)(?=\w*[a-zA-z])\w*$"
There is a good article about it here: http://nilangshah.wordpress.com/2007/06/26/password-validation-via-regular-expression/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With