Sign in to follow this  
dannielum

[.net] Regular Expression for valid variable name

Recommended Posts

I am trying to do a check for the valid variable name using Regex in .NET C#. However, this code below doesn't seem to work:
Regex regex = new Regex("[a-zA-Z_][a-zA-Z0-9_]*");
Match match = regex.Match(name);
if (match.Success)
   // valid
else
   // invalid

valid variable name should start with alphabet or "_", and follow by any number of "_", alphabet, or number characters. Can anyone good with regular expression help me? Thanks.

Share this post


Link to post
Share on other sites
static void Main(string[] args)
{
Regex regex = new Regex("^[a-zA-Z_][a-zA-Z0-9_]*$", RegexOptions.Compiled);
Random rand = new Random();
List<string> matches = new List<string>();

while (matches.Count < 100000)
{
char[] c = new char[10];
int length = rand.Next(3, 10);
for (int i = 0; i < length; i++)
c[i] = (char)rand.Next(32, 250);
string name = new string(c, 0, length);

if (regex.IsMatch(name) && !matches.Contains(name))
{
Console.WriteLine(name);
matches.Add(name);
}
}
}


Same as you had, but it matches against the whole string. Assume that the whole string is the name of the variable, though. All wrapped in a deliciously ugly test program. ;)

Share this post


Link to post
Share on other sites
Quote:
Original post by Spodi
*** Source Snippet Removed ***

Same as you had, but it matches against the whole string. Assume that the whole string is the name of the variable, though. All wrapped in a deliciously ugly test program. ;)


Thanks for your help! "^[a-zA-Z_][a-zA-Z0-9_]*$" works!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this