Tuesday, June 24, 2008

Regex Characters Digits and Underscores

Regex to validate a string is composed of only characters, numbers and underscores.

==comments==

Brackets mean match any one of:
"[abcde]" means match any one of a,b,c,d,e.

Dash between characters is a short hand for include all characters between.
"[a-z]" any lowercase letter
"[A-Z]" any uppercase letter
"[0-9]" any digit

Plus sign after a bracket means match one or more
"[a-zA-Z_0-9]+" will match any substring composed of only letter, digits or the underscore, the substring must have at least one

Dollar Sign matches the beginning of a string and Hat '^' matches the end of a string.
"$[a-zA-Z_0-9]+^" will match any substring composed of only letter, digits or the underscore, the substring must have at least one. Also there can be no characters before or after the matching substring.

==code==

public bool ValidateIdentifier(string identifier)
{
Regex re = new Regex("^[a-zA-Z_0-9]+$");
MatchCollection match = re.Matches(identifier);
if (match.Count != 1)
{
//_LastException = new Exception("Identifier must have only characters, digits and underscores");
return false;
}

return true;
}

No comments: