2

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.

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, ^\d{4}$ for a string that contains exactly and only four digits.
3

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

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.