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);
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_-]*$".
- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"
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.
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 "."
Try changing your regex to:
^[A-Za-z0-9]+$
You have in your current regex |.* this is effectively "or any charachter (including whitespace)"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With