-4

I need a regex to match any number between 0 to 100 including decimal numbers example: my expression should match 1,2,2.3 ,40,40.12 ,100,100.00 like this ..thanks in advance?

chanti
  • 431
  • 1
  • 5
  • 9

3 Answers3

2

Assuming you have to allow for a leading sign, you are best off writing

if ( /(?<![-+.\d])([-+]?\d+(?:\.\d*)?(?![-+.\d])/ and $1 >= 0 and $1 <= 100 ) { .. }

But if you are forced into using a regex, then you need

if ( /(?<![-+.\d])(([-+]?(?:100|\d\d)(?:\.\d*)?(?![-+.\d])/ ) { .. }

These pattern may well be more complex than necessary because they allow for the number appearing anywhere in the string. If you are simply checking an entire string to see if it matches the criteria then it could be much shorter

Borodin
  • 126,100
  • 9
  • 70
  • 144
  • Your regex `/(?<![-+.\d])(([-+]?(?:100|\d\d)(?:\.\d*)?(?![-+.\d])/` is incorrect. Even after I balanced the parentheses, it behaves incorrectly. – protist Oct 04 '12 at 09:04
0

This would work:

(100(\.0+))|([0-9]{1,2}(\.[0-9]+)?)

match either "100" (with optional dot plus one or more zeroes) or one or two digits, optionally followed by a dot and at least one digit.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
0

EDITED!!!

This problem was much more difficult than I initially realized. With some amount of effort, I have produced a new regex that is without error. Enjoy.

/(?<!\d)(?<!\.)(100(?:(?!\.)|(?:\.0*+|\.))(?=\D)|[0-9]?[0-9](?:\.|\.[0-9]*+)?(?=[\D]))/

This pattern will capture in $1

protist
  • 1,172
  • 7
  • 9