最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - regex compare two numbers - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Nov 6, 2011 at 11:03 kleopatra 51.5k28 gold badges102 silver badges216 bronze badges asked Nov 18, 2008 at 13:45 geeeeeeeeeekgeeeeeeeeeek 3
  • I think you'll want to give a better description, or more examples, of what you require. – RB. Commented Nov 18, 2008 at 13:47
  • Jeff's answer to this !! – Vijay Dev Commented Nov 18, 2008 at 14:13
  • Regular expressions are for matching patterns, not checking numeric values. Find a likely string with the regex, then check its numeric value in whatever your host language is (Javascript, whatever). – Andy Lester Commented Jun 2, 2013 at 5:29
Add a comment  | 

3 Answers 3

Reset to default 15

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.

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

发布评论

评论列表(0)

  1. 暂无评论