Per quelli di voi che preferiscono non andare con Regex e sono su .NET 2.0 quadro (AKA senza LINQ):
solo lettere:
public static bool IsAllLetters(string s)
{
foreach (char c in s)
{
if (!Char.IsLetter(c))
return false;
}
return true;
}
solo numeri:
public static bool IsAllDigits(string s)
{
foreach (char c in s)
{
if (!Char.IsDigit(c))
return false;
}
return true;
}
Solo numeri o lettere:
public static bool IsAllLettersOrDigits(string s)
{
foreach (char c in s)
{
if (!Char.IsLetterOrDigit(c))
return false;
}
return true;
}
solo numeri o lettere o underscore:
public static bool IsAllLettersOrDigitsOrUnderscores(string s)
{
foreach (char c in s)
{
if (!Char.IsLetterOrDigit(c) && c != '_')
return false;
}
return true;
}
Questo presuppone un alfabeto latino, dove Char.IsLetter permette di alfabeti non latini. –
Regex.IsMatch (input, "^ [a-z0-9] + $", RegexOptions.IgnoreCase); –
@TomFobear: questo è più lento di specificare esplicitamente [a-zA-Z] –