简体   繁体   English

正则表达式比较两个数字

[英]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. 我想要正则表达式对10-12是正确的,但对12-10不正确。 I mean that 10 must be smaller than 12. I want to do it in Javascript. 我的意思是10必须小于12。我想用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 > 如果输入始终为XY形式,那么为什么不使用以'-'为分隔符的split()函数,然后将两个部分与>进行比较

You can't compare numerical values using RegExps. 您无法使用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). 我在运算符上分割了字符串,然后根据发现的运算符比较两个结果数字(我假设10+1212+10都是合法的)。

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 . 因此,正则表达式肯定会帮助您识别xy但是您要求太多,无法继续推论xy之间的关系。

As often quoted; 经常引用;

Some people, when confronted with a problem, think "I know, I'll use regular expressions." 有些人在遇到问题时会认为“我知道,我会使用正则表达式”。 Now they have two problems. 现在他们有两个问题。 ( JWZ ) JWZ

Or rather, you've now got three. 或更确切地说,您现在拥有三个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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