I'm looking for a quick way (in C#) to determine if a string is a valid variable name. My first intuition is to whip up some regex to do it, but I'm wondering if there's a better way to do it. Like maybe some kind of a secret method hidden deep somewhere called IsThisAValidVariableName(string name), or some other slick way to do it that is not prone to errors that might arise due to lack of regex prowess.
A valid variable name begins with a letter and contains not more than namelengthmax characters. Valid variable names can include letters, digits, and underscores. MATLAB keywords are not valid variable names.
Valid Names A valid variable name starts with a letter, followed by letters, digits, or underscores. MATLAB® is case sensitive, so A and a are not the same variable. The maximum length of a variable name is the value that the namelengthmax command returns.
Try this:
// using System.CodeDom.Compiler; CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); if (provider.IsValidIdentifier (YOUR_VARIABLE_NAME)) { // Valid } else { // Not valid }
public static bool IsIdentifier(string text) { if (string.IsNullOrEmpty(text)) return false; if (!char.IsLetter(text[0]) && text[0] != '_') return false; for (int ix = 1; ix < text.Length; ++ix) if (!char.IsLetterOrDigit(text[ix]) && text[ix] != '_') return false; return true; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With