9

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);
KyleMit
  • 30,350
  • 66
  • 462
  • 664
user2956406
  • 167
  • 1
  • 1
  • 6
  • You see `true` because it matches solely on the `.*`, meaning: every character (except newline chars) zero to unlimited times. If you insist on a regular expression you are almost there: use `^[A-Za-z0-9]+$`. This matches on only one or more characters in the given ranges and will fail if any other character is encountered. – AutomatedChaos Nov 06 '13 at 15:21

2 Answers2

15

Try changing your regex to:

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

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

Mike Norgate
  • 2,393
  • 3
  • 24
  • 45
1

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.

Pierre-Luc Pineault
  • 8,993
  • 6
  • 40
  • 55
  • Visual Studio doesn't get "All" method. – user2956406 Nov 06 '13 at 15:15
  • @user2956406 Add `using System.Linq;` at the top of your file. If you have ReSharper you can also press ALT + ENTER, it will add the using directive automatically. – Pierre-Luc Pineault Nov 06 '13 at 15:17
  • Never made this particular test, but: Regex should be way faster then Linq both generally and particularly speaking. – hardyVeles Sep 21 '18 at 11:41
  • I think the OP meant letters and digits from the ASCII range. The (linked) documentation of `IsLetterOrDigit` states that _Valid letters and decimal digits are members of the following categories in UnicodeCategory: UppercaseLetter, LowercaseLetter, TitlecaseLetter, ModifierLetter, OtherLetter, or DecimalDigitNumber._ Checking the `DecimalDigitNumber` category shows that it contains _decimal digits or numbers_ from all sorts of languages/alphabets ... See also the following answer: https://stackoverflow.com/a/228565/1809799 The regex given in the accepted answer should accomplish exactly that. – René Nov 05 '19 at 13:21