How to validate a string, to only allow alphanumeric characters in it? (regex)
(I don't want to allow for any spaces either).
How to validate a string, to only allow alphanumeric characters in it? (regex)
(I don't want to allow for any spaces either).
Use the expression:
^[a-zA-Z0-9]*$
ie:
Regex r = new Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(SomeString)) {
...
}
^\w+$
will allow a-zA-Z0-9_
Use ^[a-zA-Z0-9]+$
to disallow underscore.
Note that both of these require the string not to be empty. Using *
instead of +
allows empty strings.
replace regex: [^A-Za-z0-9] with: empty string
depending on the language:
in vi: :%s/[^A-Za-z0-9]//g
in php: ereg_replace("[^A-Za-z0-9]", "", $string )
You could do it easily with an extension function rather than a regex ...
public static bool IsAlphaNum(this string str)
{
if (string.IsNullOrEmpty(str))
return false;
for (int i = 0; i < str.Length; i++)
{
if (!(char.IsLetter(str[i])) && (!(char.IsNumber(str[i]))))
return false;
}
return true;
}
Per comment :) ...
public static bool IsAlphaNum(this string str)
{
if (string.IsNullOrEmpty(str))
return false;
return (str.ToCharArray().All(c => Char.IsLetter(c) || Char.IsNumber(c)));
}
While I think the regex-based solution is probably the way I'd go, I'd be tempted to encapsulate this in a type.
public class AlphaNumericString
{
public AlphaNumericString(string s)
{
Regex r = new Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(s))
{
value = s;
}
else
{
throw new ArgumentException("Only alphanumeric characters may be used");
}
}
private string value;
static public implicit operator string(AlphaNumericString s)
{
return s.value;
}
}
Now, when you need a validated string, you can have the method signature require an AlphaNumericString, and know that if you get one, it is valid (apart from nulls). If someone attempts to pass in a non-validated string, it will generate a compiler error.
You can get fancier and implement all of the equality operators, or an explicit cast to AlphaNumericString from plain ol' string, if you care.