简体   繁体   中英

How to write a C# Regex to ensure a string starts with one char followed by 6 digits

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?

var regex = new Regex(@"^[SRV]\d{6}$");

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 S123456 7, 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 (ie the string matches the pattern from start to end).

^[sSvVnN]\d{6}$

将匹配指定字符的大小写

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM