Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a string is a valid variable name?

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.

like image 698
Zann Anderson Avatar asked Dec 01 '09 23:12

Zann Anderson


People also ask

How do you know if a variable name is valid?

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.

What makes a variable name valid?

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.


2 Answers

Try this:

// using System.CodeDom.Compiler; CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); if (provider.IsValidIdentifier (YOUR_VARIABLE_NAME)) {       // Valid } else {       // Not valid } 
like image 158
Gonzalo Avatar answered Sep 23 '22 00:09

Gonzalo


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; } 
like image 23
BenevolentDeity Avatar answered Sep 23 '22 00:09

BenevolentDeity