简体   繁体   中英

regex compare two numbers

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.

If the input is always of the form XY, 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.

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

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

Regex is great at syntax (ie recognising numbers), but rubbish at semantics (ie recognising meaning). So regex will definitely help you recognise xy 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM