2

我需要用 C# 编写一个正则表达式,以确保字符串以 S、R 或 V 中的一个字符开头,然后有六个以下数字,例如:“S123456”。这是我正在尝试使用的正则表达式:

@"(S|R|V)[0-9]{6}?"

但是如果我传递一个数字太多的字符串,比如“S1234567”,它就会失败。我在这里做错了什么?

4

3 回答 3

7
var regex = new Regex(@"^[SRV]\d{6}$");
于 2013-07-11T13:23:56.343 回答
7

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).

于 2013-07-11T13:26:38.043 回答
1
^[sSvVnN]\d{6}$

将匹配您指定字符的大小写

于 2013-07-11T13:29:30.743 回答