Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression For Alphanumeric String With At Least One Alphabet Or Atleast One Numeric In The String

Tags:

c#

regex

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.

like image 600
Arnab Das Avatar asked Apr 21 '11 16:04

Arnab Das


People also ask

How do I check if a string is alphanumeric regex?

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().

What does regex 0 * 1 * 0 * 1 * Mean?

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.

What is difference [] and () in regex?

[] 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 .


2 Answers

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.

like image 156
ridgerunner Avatar answered Nov 14 '22 22:11

ridgerunner


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/

like image 25
Alex Avatar answered Nov 14 '22 22:11

Alex