Neha
Neha

Reputation: 184

Regex not working in c# wpf

I want to check if entered name contains only alpha numeric data or _ or space. Like a file name.

this is my function

  public bool IsAlphaNumeric(String strToCheck)
    {
        bool res;
        Regex objAlphaNumericPattern = new Regex("^[a-zA-Z0-9_]+$");
        res=objAlphaNumericPattern.IsMatch(strToCheck);
        return res;
    }

but it returns false even for strings like "abc def" i.e . it allows only spaceless strings like "abc12".. can you give the correct code..or what is wrong in my code

Upvotes: 0

Views: 242

Answers (2)

swapnil
swapnil

Reputation: 1192

Regex objAlphaNumericPattern = new Regex("^[a-zA-Z0-9_\\s]+$");

this works fine for me.

Upvotes: 1

vks
vks

Reputation: 67968

 ^[a-zA-Z0-9_\s]+$

or you can also use

 ^[a-zA-Z0-9_ ]+$

Add \s to include space as well.

Upvotes: 0

Related Questions