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 []
?
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 []
?
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
Actually, your expression is parsed as
^
- start of string(
- start of a capturing groupABC
- 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.