开发者

Only match regular expression in c# string

I am not too good with regular expressions so this might be an obvious question.

I want my expression to match if a certain number of characters are found and fail if any extra characters are present. For example if I have a string tha开发者_开发百科t should have 4 digits the following should be true.

1234 - match

ab1234cd - does not match

012345 - does not match

What I have so far is \d{4} but my understanding is that this would just match any string that has 4 digits together in it anywhere. I want to match only if a string contains 4 digits and nothing else.

Any help would be appreciated. Thanks.


Use ^ and $ to mark the start/end of the string.


Depending on how you are implementing it (single line mode or multiline mode) you can use something similar to:

^\d{4}$

To only match the (beginning of the string) four digits (end of string).


\b[0-9]{4}\b or ^\d{4}$ should both work. Maybe I could expand a little bit on what GrayWizardx said (just in case you do not use Regular Expressions in C# that much), the regular expressions provided above look for lines that have only 4 digits. By default (if memory serves me well), the regular expression engine looks at the first line only, so if you have a string made from more than 1 line and you would like to check the entire string (for instance, the string has been loaded from a file), you would add the option RegexOptions.MultiLine. in this way, the engine will take a look at the other lines as well.

Hope this has been helpful :)


I believe \b[0-9]{4}\b should do the trick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜