Jump to content

  • Log In with Google      Sign In   
  • Create Account

[.net] Regular Expression for valid variable name


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
4 replies to this topic

#1 dannielum   Members   -  Reputation: 167

Like
0Likes
Like

Posted 25 October 2008 - 06:06 AM

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.

Sponsor:

#2 SiCrane   Moderators   -  Reputation: 9670

Like
0Likes
Like

Posted 25 October 2008 - 06:35 AM

Define "doesn't seem to work".

#3 dannielum   Members   -  Reputation: 167

Like
0Likes
Like

Posted 25 October 2008 - 06:41 AM

It doesn't catch string containing special characters like "^abc"

#4 Spodi   Members   -  Reputation: 642

Like
0Likes
Like

Posted 25 October 2008 - 07:34 AM

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. ;)
NetGore - Open source multiplayer RPG engine

#5 dannielum   Members   -  Reputation: 167

Like
0Likes
Like

Posted 25 October 2008 - 08:15 AM

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!




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS