Reputation:
I have to check if a string contains only letters, digits and underscores. This is how I tried but it doesn't work:
for(int i = 0; i<=snameA.Length-1; i++)
{
validA = validA && (char.IsLetterOrDigit(snameA[i])||snameA[i].Equals("_"));
}
Upvotes: 12
Views: 24328
Reputation: 411
You could try matching a regular expression. There is a built in type for "letters, digits and underscores", which is "\w".
Regex rgx = new Regex(@"\w*");
rgs.IsMatch(yourString);
If you require 1 or more, then use "\w+".
Further information here: Regex.IsMatch
Upvotes: 3
Reputation: 186668
First, letter is a bit vague term: do you mean a..z
and A..Z
characters or letter could belong to any alphabet, e.g. а..я
and А..Я
(Russian, Cyrillic letters). According to your current implementation, you want the second option.
Typical solution with loop is to check until 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 (i.e. non-letter/digit symbol found)
break; // <- do not forget this: there's no use to check other characters
}
However you can simplify the code with either Linq:
validA = sname.All(ch => Char.IsLetterOrDigit(ch) || ch == '_');
Or regular expression:
validA = Regex.IsMatch(sname, @"^\w*$");
Upvotes: 1
Reputation: 7766
you can use regex
Regex regex1 = new Regex(@"^[a-zA-Z0-9_]+$");
if(regex1.IsMatch(snameA))
{
}
Upvotes: 5
Reputation: 29431
I love Linq for this kind of question:
bool validA = sname.All(c => Char.IsLetterOrDigit(c) || c.Equals('_'));
Upvotes: 15
Reputation: 1203
I would use a Regex
string pattern = @"^[a-zA-Z0-9\_]+$";
Regex regex = new Regex(pattern);
// Compare a string against the regular expression
return regex.IsMatch(stringToTest);
Upvotes: 3
Reputation: 156938
You are assigning validA
every time again, without checking its previous value. Now you always get the value of the last check executed.
You could 'and' the result:
validA &= (char.IsLetterOrDigit(snameA[i]) || snameA[i] == '_');
This would mean you still run all characters, which might be useless if the first check failed. So it is better to simply step out if it 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 == '_');
Upvotes: 10