Regular expression to match a percentage with decimal?

前端 未结 3 617
你的背包
你的背包 2020-12-20 07:01

I\'m attempting to build a regular expression (.NET) to match a percentage with 4 decimal places. The 4 decimal places are required. The range looks like:

0.         


        
相关标签:
3条回答
  • 2020-12-20 07:30

    I would do something like this:

    ^((([0-9]|[1-9]\d)\.\d{4})|100\.0000)$
    

    Proof

    0 讨论(0)
  • 2020-12-20 07:42

    Just treat the 100.0000 possibility as a separate case. It's easy to match that (100\.0000), and it's easy to match the rest ([1-9]?\d\.\d{4}), so with the two as alternates you get:

    ^(100\.0000|[1-9]?\d\.\d{4})$
    

    (Assuming you want it to be the whole text, otherwise leave out the ^ and the $.

    0 讨论(0)
  • 2020-12-20 07:57

    See it in action:

    ^(0|[1-9]\d?)\.\d{4}|100\.0000$
    

    Matches:

    0.0001
    100.0000
    42.4214
    1.0000
    

    Doesn't match:

    100.0135
    042.4214
    001.0000
    000.0000
    1000.0000
    2000.0000
    300.0000
    
    0 讨论(0)
提交回复
热议问题