Check if the string contains only letters, numbers, and underscores

I need to check if a string contains only letters, numbers and underscores. This is how I tried, but it does not work:

for(int i = 0; i<=snameA.Length-1; i++) { validA = validA && (char.IsLetterOrDigit(snameA[i])||snameA[i].Equals("_")); } 
+8
c # regex linq
source share
6 answers

I love Linq for this question:

 bool validA = sname.All(c => Char.IsLetterOrDigit(c) || c.Equals('_')); 
+6
source share

You assign validA each time again without checking its previous value. Now you always get the value of the last check.

You can "and" the result:

 validA &= (char.IsLetterOrDigit(snameA[i]) || snameA[i] == '_'); 

This would mean that you are still running all the characters that might be useless if the first check failed. Therefore, it is better to simply exit if this fails:

 for(int i = 0; i<=snameA.Length-1; i++) { validA = (char.IsLetterOrDigit(snameA[i]) || snameA[i] == '_'); if (!validA) { break; } // <-- see here } 

Or with LINQ:

 validA = snameA.All(c => char.IsLetterOrDigit(c) || c == '_'); 
+9
source share

you can use regex

 Regex regex1 = new Regex(@"^[a-zA-Z0-9_]+$"); if(regex1.IsMatch(snameA)) { } 
+4
source share

You can try matching regular expression. There is a built-in type for "letters, numbers, and underscores," which is "\ w".

 Regex rgx = new Regex(@"\w*"); rgs.IsMatch(yourString); 

If you need 1 or more, use "\ w +".

More information here: Regex.IsMatch

+3
source share

I would use regex

 string pattern = @"^[a-zA-Z0-9\_]+$"; Regex regex = new Regex(pattern); // Compare a string against the regular expression return regex.IsMatch(stringToTest); 
+2
source share

First, a letter is a slightly vague term: you mean a..z and a..z characters or a letter can belong to any alphabet, for example. .. and .. (Russian, Cyrillic letters). According to your current implementation, you need the second option.

A typical solution with a loop is to check before the first counter example:

  Boolean validA = true; // true - no counter examples so far // Why for? foreach is much readble here foreach(Char ch in sname) // "!= '_'" is more readable than "Equals"; and wants no boxing if (!char.IsLetterOrDigit(ch) && ! (ch != '_')) { Boolean validA = false; // counter example (ie non-letter/digit symbol found) break; // <- do not forget this: there no use to check other characters } 

However, you can simplify the code with Linq:

  validA = sname.All(ch => Char.IsLetterOrDigit(ch) || ch == '_'); 

Or regex:

  validA = Regex.IsMatch(sname, @"^\w*$"); 
0
source share

All Articles