user2956406
user2956406

Reputation: 177

regular expression allow Latin letters and digitals number and disallow space

I have regular expression allow only latin letters and digitals number and disallow space. But this expression miss string where exist space. In my code I need see true and false. But I see true and true. How it fixed?

String str1="5asdfEDadgs2";
String str2 = "5 asdfgsadgs2";
String reg=@"^[a-zA-Z]|[0-9]|.*$"

bool res = Regex.Match(str1,reg). Success; //Must show true
bool res2 = Regex.Match(str2, reg).Success; //Must show false

Console.WriteLine(res);
Console.WriteLine(res2);

Upvotes: 10

Views: 13457

Answers (2)

Mike Norgate
Mike Norgate

Reputation: 2431

Try changing your regex to:

^[A-Za-z0-9]+$

You have in your current regex |.* this is effectively "or any charachter (including whitespace)"

Upvotes: 15

Pierre-Luc Pineault
Pierre-Luc Pineault

Reputation: 9191

You do not really need a Regex for that, you can simply use char.IsLetterOrDigit and a little bit of LINQ :

String str1="5asdfEDadgs2";
String str2 = "5 asdfgsadgs2";

bool res = str1.All(char.IsLetterOrDigit); //True
bool res2 = str2.All(char.IsLetterOrDigit); //False

You could also write the equivalent str1.All(c => char.IsLetterOrDigit(c)) but I find the method group form much cleaner.

Upvotes: 1

Related Questions