开发者

.NET regex decimal numbers

I have to validate using regex decimal number between 00.00 to 35.35 with following simple assumptions(I am using C#).

1) leading zeros are not required(optional). 2) 2 decimals are always required.

In other words, it should be a开发者_运维技巧 decimal number within a range with 2 decimal points.

Examples of valid numbers are: 0.00, 00.00, .67, 2.89 and should fail on those numbers: 8.9999(4 decimals), 65.00(out of range)

I had no difficulty to validate 2 decimal points but don't know how to do the range? Is this something that even can be done using regex?


Seriously. Use RegEx to check that the input matches ^\d{1,2}\.\d{2}$, then convert it into a number and check 0 <= x && x <= 35.35. RegEx is not designed to be a calculator.


If you insist:

^(?:(?:[012]?\d|3[0-4])\.\d{2}|35\.(?:[012]\d|3[0-5]))$


I would use Decimal.TryParse. E.g.:

    private const decimal min = 0.0M;
    private const decimal max = 35.35M;
    static bool inRange(string s)
    {
        Decimal d = new Decimal();
        if (Decimal.TryParse(s, out d))
        {
            return d > min && d < max;
        }
        else
            return false;
    }


Try this regular expression:

^(0?\d|[12]\d|3[0-4])?\.\d\d$|^35\.([02]\d|3[05])$
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜