1

I have this line to match ABC123457 or 123457

Regex regex = new Regex(@"^(ABC|[])[0-9]{7}$");

All online-regex-tester says that is correct and it working as expected.
Maybe a bug in System.Text.RegularExpression because of the empty []?

akop
  • 5,981
  • 6
  • 24
  • 51
  • Even when this is parsed as valid, `[]` is just the same as the empty string. Just omit it entirely (or use the `?` quantifier as shown by Wiktor). – Konrad Rudolph Dec 14 '17 at 13:47

1 Answers1

4

You cannot use [] in a .NET regex to denote an empty string. If you pasted your regex into a .NET regex testing site you would see

enter image description here

Actually, your expression is parsed as

  • ^ - start of string
  • ( - start of a capturing group
  • ABC - a literal substring
  • | - or
  • [ - start of a character class
    • ])[0-9 - ], ), [, digits
  • ]{7} - 7 occurrences
  • $ - end of string.

There is no ending ) here.

To fix the current pattern, just use an optional non-capturing group:

Regex regex = new Regex(@"^(?:ABC)?[0-9]{7}$");
                           ^^^^^^^^

See the regex demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    @user6537157 It is a [non-capturing group](https://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group-what-does-a-question-mark-followed-by-a-colon). If you need to access Group 1 value (`match.Groups[1].Value`, to check if it is empty or `ABC`), use a capturing group, as you did in the original pattern. I surmised you used a group just for an alternation, sorry if that is not what you meant. – Wiktor Stribiżew Dec 14 '17 at 13:45
  • Its all fine, the link explains what I wanted to know. :) – akop Dec 14 '17 at 13:49