mcnarya
mcnarya

Reputation: 871

Matching numbers with decimals in regular expression

I want to see if a number that I have is between two other numbers. Let's say my number is 0.17. I would like the regular expression to be something like this: [0.15-0.22]. Could someone help get me on the right track?

Upvotes: 1

Views: 565

Answers (3)

André Laszlo
André Laszlo

Reputation: 15537

I think that you should rethink your approach a bit. Instead of trying to match a range in your regular expression (which is probably doable, but not very beautiful), try to match the number you're looking for and then test if it's in the correct range using your favorite language. Here's an Python3 session for you:

>>> import re
>>> a_string = "A number can be 0.17 or 0.163 but certainly not 0.47 or -1.2!"
>>> matches = re.findall(r'(-?[0-9]+\.?[0-9]+)', a_string)
>>> print(matches)
['0.17', '0.163', '0.47', '-1.2']
>>> nums = [n for n in [float(c) for c in matches] if n < 0.22 and n > 0.15]
>>> print(nums)
[0.17, 0.163]

Upvotes: 1

agent-j
agent-j

Reputation: 27913

Here's a regex to get you started, but it's a lot of work and unlikely to be very rewarding. Go with @Dark Slipstream's idea if you can.

(?<!\d)0?\.(?:1[5-9]|2[0-1]|220*([^1-9]|$))

See ;-) That's why regex isn't designed to solve your problem.

It sounds like you want a generic solution, and so while it is posible, you haven't written down nearly enough detail. You'll need to think about the precision of numbers you are looking for, and if you want an inclusive or exclusive range (or whatever is easiest). BTW, the easiest would be inclusive on the left side and exclusive on the right (in interval notation, [0.15 - 0.22)), because you can simply subtract .01 from .22 and then break apart the problem into 2-3 parts \.(?:1[5-9]|.2[0-1]).

Upvotes: 1

Nahydrin
Nahydrin

Reputation: 13507

If your sure that your number is always a valid number, then you don't need regular expressions. Just check if $num < 0.22 && $num > 0.15.

If your number may not be valid, filter it using regex:

preg_match( "/[0-9]*(\.[0-9]*)/", $num, $matches );
$num = $matches[0];

Upvotes: 2

Related Questions