5

I need help with a regex matching a number. I need up to 3 digits after the dot (.):

12345    ok
12       ok
12.1     ok
12.12    ok
12.123   ok
12.1234  Error
1.123456 Error

how to do it? Thanks in advance.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
Gold
  • 60,526
  • 100
  • 215
  • 315

5 Answers5

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

Explanation:

\d+        # multiple digits
(?:        # start non-capturing group  
  \.       # a dot
  \d{1,3}  # 1-3 digits
)?         # end non-capturing group, made optional
Tomalak
  • 332,285
  • 67
  • 532
  • 628
9
^\d+(\.\d{1,3})?$
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
3

You can try:

^\d+|(\d+\.\d{1,3})$
  • \d - Single digit
  • \d+ - one or more digits, that is a number.
  • \. - dot is a metachar..so to match a literal dot, you'll need to escape it.
  • {1,3} - between 1 to 3 (both inclusive) repetitions of the previous thing.
  • ^ and $ - Anchors so that we match entire thing not just part of something.
codaddict
  • 445,704
  • 82
  • 492
  • 529
1

Are you sure you need regex to solve the problem you are having? How about:

bool ContainsAtMostThreeNumbersAfterDot(string str)
{
  int dotIndex = str.IndexOf(".");
  float f;
  return float.TryParse(str, out f) && str.Length - dotIndex < 3;
}

This code is nor complete or 100% correct (take is just as an idea and handle the specific cases yourself), but IMHO, it expresses the intent a lot more clearly than using a regex to solve a problem that does not need regex at all.

Marek
  • 10,307
  • 8
  • 70
  • 106
  • ...reads clearly to anyone knowing regex. Does not express intent at all for anyone not familiar with regular expressions and is an overkill of the strength of regular expressions for a problem that has a much easier and readable solution. – Marek Mar 04 '10 at 09:43
  • How is this an overkill? To those who knows regex, this application falls perfectly on the sweet spot of the language. And you can't possibly be serious about your solution being easier and more readable. I don't even know what `TryParse` does without looking up the API. – polygenelubricants Mar 04 '10 at 11:15
-1

REGEX

^[\d]*[\.]\d{3}$

Examples:

ok -- 1.000
ok -- 10.000
ok -- 100.000
ok -- 1000.000
ok -- 10000.000

error -- 10
error -- 10.0
error -- 10.00
error -- 10,000

EDITED (2019-09-12)

Only 3 decimal places accepted now. Delimited by Dot.