开发者

How to write .NET regular expression for floating value (5,2)?

开发者 https://www.devze.com 2023-02-09 09:20 出处:网络
Hi i need to write a regular expression for float value (5,2) As per my understanding (5,2) means Total length cannot exceed 5 digits i.e. 999.99

Hi i need to write a regular expression for float value (5,2)

As per my understanding (5,2) means

  1. Total length cannot exceed 5 digits i.e. 999.99
  2. Digits before decimal is 3 and after decimal is 2 i.e开发者_开发技巧. 999.99

I wrote this: ValidationExpression="(^\d{0,3}[.]?\d{0,2}$)" but this is accepting 9999 and 99999 which is wrong because in both case before decimal is more than 3 digits.

Please help?


For your case of 0-3 digits before dot and 0-2 after dot:

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

Notice the subtle difference of requiring at least one number after the dot. If you allow 0 numbers after the dot, you will match just ., which is not a number.

The general convention on floating point numbers is to allow starting with the decimal separator and write just the decimal part (.e.g .123 means 0.123), so I'd recommend you to do that unless you have other requirements to regard.

This will match:

.1
0.1
0.01
100.02
-3.01

If you want to, you can use \d instead of [0-9].

NOTE: If you need multi-language support, different locales have different decimal separators (Norwegian has ,, for instance).

General matcher for floating point numbers (from regular-expressions.info):

[-+]?[0-9]*\.?[0-9]+

Validation ("is this string a floating point number") needs anchoring:

^[-+]?[0-9]*\.?[0-9]+$

And finally, here's an expression allowing exponents (e.g. -0.1e-9):

[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)? 


I'd suggest

ValidationExpression = @"^\d{1,3}(?:\.\d{1,2})?$)"

This requires at least one (integer) digit, and if there is a decimal part, it has to be one or two digits long. So this will match

1
1.0
0.12
999.99

but fail

.1
1.
000001.0
9999


Remove the question mark, it made the dot optional.

If you want a regex that match "123.45", "123.4" and "123" but NOT "123.", use this:

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

in wich the optional part is the entire decimal part of the number


\d{0,3} means "between zero and 3 digits"

You should use

(^\d{3}\.\d{2]$)

If you do not want leading zeroes, use this one instead:

(^[1-9]\d{2}\.\d{2]$)


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

means 1-12 digits before separator, then separator (dot or comma), then 0-2 digits after separator, i.e.:

9
99
999,1
9999,22
(and the same with dot)
0

精彩评论

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

关注公众号