C# .NET - Regular Expression for Password to allow alphanumeric characters

Asked By abinav shankar on 15-Jan-12 11:08 AM


I want a regularfield expression for password which allows alphanumeric characters with one special characters


[)ia6l0 iii replied to abinav shankar on 15-Jan-12 11:27 AM
You might have to tweak this a little. "-&_ " takes care of special character.
^(?:(?>[a-zA-Z0-9]+)(?:[-&_ ](?![-&_ ]|$))?)+$

Or, you can use the following one to check for alphanumeric characters and then add another one for "one" special character.
D Company replied to abinav shankar on 15-Jan-12 11:42 AM
Hello Abinav

try this

^(?:(?>[0-9A-Za-z]+)(?:[-&_ ](?![-&_ ]|$))?)+$



{1,1 } is for allowing only one special charecter

kalpana aparnathi replied to abinav shankar on 15-Jan-12 12:08 PM

Pass it through multiple regexes if you can. It'll be a lot cleaner than those look-ahead monstrosities :-)


Though some might consider it clever, it's not necessary to do everything with a single regex (or even with any regex, sometimes - just witness the people who want a regex to detect numbers between 75 and 4093).

Would you rather see some nice clean code like:

if not checkRegex(str,"^[0-9]+$")
    return false
val = string_to_int(str);
return (val >= 75) and (val <= 4093)

or something like:

return checkRegex(str,"^7[5-9]$|^[89][0-9]$|^[1-9][0-9][0-9]$|^[1-3][0-9][0-9][0-9]$|^40[0-8][0-9]$|^409[0-3]$")
kalpana aparnathi replied to abinav shankar on 15-Jan-12 12:10 PM
Try this:

Regex :

Riley K replied to abinav shankar on 15-Jan-12 09:02 PM

The below one should work


This requires at least one digit, at least one alphabetic character, no special characters, and from 8-20 characters in length. 

smr replied to abinav shankar on 15-Jan-12 11:16 PM

I would guess that by letter you mean 'a-z' or 'A-Z', by digit you mean '0-9' and by symbol you mean any other printable ASCII character. If so, try this:

static bool IsLetter(char c)
  return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
static bool IsDigit(char c)
  return c >= '0' && c <= '9';
static bool IsSymbol(char c)
  return c > 32 && c < 127 && !IsDigit(c) && !IsLetter(c);
static bool IsValidPassword(string password)
     password.Any(c => IsLetter(c)) &&
     password.Any(c => IsDigit(c)) &&
     password.Any(c => IsSymbol(c));