Regex regex = new Regex("[a-zA-Z_][a-zA-Z0-9_]*");
Match match = regex.Match(name);
if (match.Success)
// valid
else
// invalid
[.net] Regular Expression for valid variable name
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:
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.
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. ;)
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement