2

I need a regex in .NET that represents a decimal number with up to 9 digits to the left of the decimal point and 1 or 0 digits to the right. What I have isn't working.

Here is what I have:

@"^\d{0,9}[\.\d]{0,1}$"

What am I doing wrong? This regex is currently allowing 10 digits to the left of the decimal point and no digits to the right although it does accept strings like this --> 12.

2 Answers 2

4

Well you have a character class [\.\d] and you are saying :

please match one or zero of either a . or a digit.

What you really want to do however would be this :

^\d{0,9}(\.\d)?$

This says from the start of the string match 0 to 9 digits (maybe you need to do this {1,9} because as it stands now an empty string will also match), followed by maybe a dot with a digit and then the end of the string.

3
  • Good explanation - thank you. I'm still trying to perfect my understanding of regex.
    – novacara
    Oct 28, 2011 at 16:41
  • A character class is a logic or. It matches a single character of all the characters inside it, in an unspecified order. So even [\.\d]{2} would have been wrong since it could match 2. or .. or .2 or 22. Accept the answer if it solved your problem.
    – FailedDev
    Oct 28, 2011 at 16:43
  • I did. It makes you wait 10 minutes.
    – novacara
    Oct 28, 2011 at 16:52
0

It should say

^\d{1,9}(\.\d)?$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.