regex compare two numbers

﹥>﹥吖頭↗ 提交于 2019-12-29 09:32:47

问题


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.


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/298753/regex-compare-two-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!