Jump to content
  • Advertisement
Sign in to follow this  
dannielum

[.net] Regular Expression for valid variable name

This topic is 3554 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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 = (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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!