tags:

views:

90

answers:

4

Hi,

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

+6  A: 

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

EricLaw -MSFT-
Yep, `^\d{4}$` for a string that contains exactly and only four digits.
JMD
This works, thanks for the quick answer
Matt
+3  A: 

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

GrayWizardx
A: 

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

Josh
+1  A: 

\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 :)

npinti