Regular expression to match a percentage with deci

2020-02-13 05:39发布

问题:

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.0001 to 100.0000 

So far, I've come up with:

(?:[^0]+[1-100]{1,3})\.(?:\d{4})

However, I'm a bit unsure on how to add a few other requirements to this expression. I need:

  • No leading zeroes before the decimal point. 42.4214 is allowed, 042.4214 is not. 1.0000 is allowed but 001.0000 is not. Etc..
  • Up to 3 characters allowed before decimal without leading zeroes.
  • If the number before the decimal is 100, do not allow the number after the decimal to be anything other than 0000, so 100.0000 is allowed, but 100.0135 is not allowed. (Is this even possible with a regex?)

Help is appreciated!

回答1:

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 $.



回答2:

I would do something like this:

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

Proof



回答3:

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