views:

931

answers:

4

can i somehow compare two numbers in regex? i want regex that is correct for 10-12, but incorrect for 12-10. I mean that 10 must be smaller than 12. I want to do it in Javascript.

+2  A: 

I wouldn't use regex for this. I'd split the string on the operator, then compare the two resulting numbers based on what operator I found (I'm assuming 10+12 and 12+10 would both be legal).

Bill the Lizard
I mean that 10 must be smaller than 12
geeeeeeeeeek
Regex is used for matching patterns, not comparing values. I'd just split the string and use < or > to compare the two resulting numbers.
Bill the Lizard
+12  A: 

If the input is always of the form X-Y, then why not use the split() function with '-' as the delimiter and then compare the two parts with >

You can't compare numerical values using RegExps.

Adam Pope
+1 for your psychic powers in determining what the asker really wanted.
Paul Tomblin
You might extract the numbers using a regex; you can't do the comparison. Regexes are not the universal problem solving tool.
Jonathan Leffler
I think I knew what he meant, but it took me as long to formulate a response that you had already answered :)
warren
+1  A: 

The problem here is that you're trying to roll two problems into one.

Regex is great at syntax (i.e. recognising numbers), but rubbish at semantics (i.e. recognising meaning). So regex will definitely help you recognise x-y but you're asking too much to then move on to reason about the relationship between x and y.

As often quoted;

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. (JWZ)

Or rather, you've now got three.

Unsliced
A: 

Jeff's answer to this !!

Vijay Dev