开发者

Regex to match numbers 0-99.999

I need a regex that that matches numbers between 0 and 99.999 (99,999 is also valid).

Valid example开发者_高级运维s:

1,1
99.9
12.876
1,777

Invalid examples:

9837,83
-12,24
11.1112


^\d{1,2}(?:[.,]\d{1,3})?$

should do.

Explanation:

^         # anchor the match at the start of the string
\d{1,2}   # match one or two digits
(?:       # optionally match the following group:
 [.,]     # a . or ,
 \d{1,3}  # 1-3 digits
)?        # end of optional group
$         # anchor the match the end of the string


If you are wanting to check a number is within a certain range you should not use Regex, it is too far removed from the logic of what you are doing and hard to debug. I would first replace commas with decimal points. Then check range.

eg (Javascript)

function isValid(inputString)
{
   var number=parseFloat(inputString.replace(',','.'));
   return (number>=0 && number <=99.999);
}

Updated Answer

The above solution does not account for the OP's requirement to have no more than 3 decimal places of precision.

function isValid(inputString){
   var number=parseFloat(inputString.replace(',','.'));
   validPrecision = true;
   if (inputString.split('.')[1]) {
       validPrecision=inputString.split('.')[1].length<=3;}
   return (number>=0 && number <=99.999 && validPrecision);
};


Will this work ?

[0-9]{1,2}[.,][0-9]{1,3}

this matches stuff similar to this:

  • 0.0 / 01,1
  • 99,999 / 09.009

but not stuff like this:

  • .0 / ,1 / 1 / 01
  • 099,999 / 09.0090

hope it helps.


The following will work:

^\d{1,2}((,|.)\d{1,3})?$
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜