2

How can I write a regular expression that validates an input text box that should contain only decimal values? The value can have at max 3 decimals (but also none) with comma as the separator.

For example, these values given below are valid:-

1,234
1,23
1,2
1

These are not valid:

1,2345 (too many decimal numbers)
A (a letter is not a number)
  (a space or string empty)
1.234 (used a dot instead of a comma)
1
  • Is ,1 valid, for that matter?
    – Tory
    Aug 26, 2013 at 19:21

4 Answers 4

7

Try something like this:

\d+(?:,\d{1,3})?

Explained:-

\d+        # multiple digits
(?:        # start non-capturing group  
  ,        # a comma
  \d{1,3}  # 1-3 digits
)?         # end non-capturing group, made optional
1
  • 1
    +1 this is the right answer, but the non-capture group really just adds unnecessary complication IMO Aug 27, 2013 at 1:49
2

You could use a pattern like this:

[0-9]+(,[0-9]{1,3})?
2
  • 1
    Thank you, could be a solution. L
    – Ciupaz
    Aug 26, 2013 at 19:09
  • 1
    I like this one, for a starter in regexes, this solution is the most straight forward. Aug 27, 2013 at 5:57
2

How about @"\d+,?\d{0,3}": 1 or more digits, then an optional comma, then 0 to 3 more digits. This assumes that you allow any number of digits before the comma. In your examples you only have one, in which case you would want to remove the +.

If the value 1, is not valid, you'll have to move the ? to the end: @"\d+(,\d{1,3})?"

3
  • This seems to match 1, which I believe is a mistake. Aug 27, 2013 at 1:47
  • @pguardiario: The OP didn't answer that question. It's quote possible that it's valid.
    – Gabe
    Aug 27, 2013 at 2:24
  • That's better, but now you've just repeated Rahul's answer. Aug 27, 2013 at 2:39
1

Note if you only want one character before the decimal, remove the +

^\d+(,(\d?){3})?$


^   //start
\d+   //one or more decimal digits
(,(\d?){3})?    //a comma, followed by up to 3 decimal digits, optionally
$    //end

If you don't want 1, to be accepted, then the middle section can be (,\d(\d?){2})?

2
  • @pguardiario I'm pretty sure it doesn't... I tested it pretty thoroughly. Did you? The ? In the second clause makes each of the 3 decimals optional, such ajar you don't need {1,3} Aug 27, 2013 at 7:32
  • (Sorry from the typos, typed on my phone) Aug 27, 2013 at 7:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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