C# Regex specify allowed start and end condtions

Viewed 48

I'm trying to create a regex expression with the following requirements:

The value:

  1. Must start with a-z or _, numbers are OK after the first character
  2. Can have parentheses if they are opened and closed with number inside at the end of string, i.e SomeVar(10) is OK, SomeVar(10 is not OK.
  3. Can have a . but only one at a time, and only between letters or numbers. SomeVar.InnerVar is OK, SomeVar..Innevar is not OK.

My try at the regex:

  1. [a-zA-Z_]
  2. ??
  3. ??
2 Answers

Assuming you want to match an entire string, you may use something like the following:

^[a-zA-Z_](?:\w|(?<=\w)\.(?=\w))*(?:\(\d+\))?$

Demo.

If you want to match partial strings, you'd need to decide what boundaries are allowed. Otherwise, "SomeVar(10" would have a match (i.e., what comes before (), for example.

Notes:

  • \w matches a lowercase/uppercase letter, a digit, or an underscore. But it also matches Unicode letters and numbers. If you don't want that, you could use [a-zA-Z0-9_] instead.

  • Similarly, \d matches any Unicode digit. You either use it or use [0-9] depending on your requirements.

Use

^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*(\([^()]*\))?$

See proof.

  1. [a-zA-Z_][a-zA-Z0-9_]* - a letter or underscore, then zero or more letters, digits, underscores
  2. (\([^()]*\))? - optional group, parens may be present or absent
  3. (\.[a-zA-Z_][a-zA-Z0-9_]*)* - dot is allowed between letter/digit/underscore.
Related