Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

regex - Regular expression to match a percentage with decimal?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...