Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression allow Latin letters and digitals number and disallow space

Tags:

c#

regex

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);
like image 302
user2956406 Avatar asked Nov 06 '13 14:11

user2956406


People also ask

How do I allow only letters and numbers in regex?

You can use regular expressions to achieve this task. In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".

Why * is used in regex?

- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"

What is\\ d in r?

In the regular expression above, each '\\d' means a digit, and '. ' can match anything in between (look at the number 1 in the list of expressions in the beginning). So we got the digits, then a special character in between, three more digits, then special characters again, then 4 more digits.

How do you denote special characters in regex?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "."


2 Answers

Try changing your regex to:

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

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

like image 135
Mike Norgate Avatar answered Nov 15 '22 01:11

Mike Norgate


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.

like image 22
Pierre-Luc Pineault Avatar answered Nov 14 '22 23:11

Pierre-Luc Pineault