Reputation: 13440
I need to write a Regex in C# to ensure that a string starts with one character of either S, R, or V, and then has six following digits, like this: "S123456". Here is the regular expression I'm trying to use:
@"(S|R|V)[0-9]{6}?"
But if I pass a string with one too many digits, like "S1234567", it fails. What am I doing wrong here?
Upvotes: 2
Views: 1928
Reputation: 2449
Three options, that depend on what you want to achieve:
Just for matching the string:
[SRV]\d{6}
For finding that string as a separated "word":
\b[SRV]\d{6}\b
For the regex to match the full string (I think this is what you need):
^[SRV]\d{6}$
EDIT:
Your regexp "fails" because it's just looking for your pattern in the string (as my first example). If the string is S1234567, the engine matches the bold part (from S to 6), so it reports a success. You have to use anchors (my third example) if you want the string just to contain your pattern and nothing else (i.e. the string matches the pattern from start to end).
Upvotes: 7
Reputation: 2047
^[sSvVnN]\d{6}$
Will match lower and upper case of your specified characters
Upvotes: 1