views:

399

answers:

3

Is there a regex that would validate a percentage value to 2 decimal places?

I have a regex for two decimal places, but don't know how to stop values above 100. e.g. 100.01 is validated with my regex.

+5  A: 

In Perl:

/(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/

or you can just add an extra if comparing 100 exactly :)

DVK
Nicely done. It works with my test cases... http://regexhero.net/tester/?id=6807190b-cc82-4dd4-8864-05ce8c0c3b4f
Steve Wortham
Looks like it works on the link provided, but can get it to work in my app. ASP.Net MVC vlaidation using data annotation:[RegularExpression(@"/(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/")]
littlechris
Yo can refactor this for better efficiency. The two parts before and after the | share an initial prefix and postfix, and it includes ^ and $. By making common parts common, you reduce the amount of backtracking needed when a part fails to match.
MSalters
@littlechris - I'm not really familiar with ASP, sorry. Your initial question's tag was not .net specific. As stated, this was Perl - I'm unsure of the portability to .net
DVK
thnkas DVK. my mistake I thought regex where pretty standard. Cheers! +1
littlechris
@littlechris - Try removing the forward slash at the beginning and end. It should work just fine in .NET (that's what Regex Hero is using).
Steve Wortham
Duh... slashes are Perl RegEx operator. The pattern is inside the slashes. Sorry for confusion.
DVK
A: 

Try this one:

\d{1,2}\.\d{2}

That gives you a one digit or two digit number followed by exactly two decimal places. If you want to allow tenths as well (ala 10.1) then try this:

\d{1,2}\.\d{1,2}
Tony Miller
I always hated 100%. ;)
Dominic Rodger
That solution misses the value '100' or '100.00'.
Bryan Oakley
Durr, I kept reading that the OP did NOT want 100.00. Oh well, perhaps another time...
Tony Miller
A: 

/^(?:100(?:.0(?:0)?)?|\d{1,2}(?:.\d{1,2})?)$/

Works with:

  • 100
  • 100.0
  • 100.00
  • 99.99
  • 0.01
  • 5

etc.

Xetius