简体   繁体   English

JavaScript RegEx匹配无效数字

[英]JavaScript RegEx Matches Invalid Number

I am getting inconsistent results when using JavaScript's RegEx to validate numbers with a decimal place. 使用JavaScript的RegEx验证小数点后的数字时,结果不一致。 The goal is to have any combination of digits followed by a decimal point and two more digits. 目标是使数字任意组合,后接小数点和另外两位。 It works fine except with numbers in the thousands (no separators). 它可以正常工作,除非有数千个数字(没有分隔符)。

This is the expression I'm using: 这是我正在使用的表达式:

^[0-9]+(\.[0-9][0-9])$

Valid numbers: 有效数字:

10.99
0.75
999.99
5000.99
...etc

Invalid Numbers: 无效的数字:

1000
.75
0
...etc

The problem is that it matches whole numbers in the thousands. 问题在于它匹配成千上万的整数。 This is for an internal application so I'm not concerned about using additional separators. 这是针对内部应用程序的,因此我不必担心使用其他分隔符。 I've tested the expression out with tools like http://regexpal.com/ which gives me the results that I need, so it appears that there is something in the JS causing the issue. 我已经使用诸如http://regexpal.com/之类的工具测试了该表达式,该工具可以为我提供所需的结果,因此看来JS中存在某些问题。

You can duplicate the problem here: http://jsfiddle.net/hcAcQ/ 您可以在此处重复该问题: http : //jsfiddle.net/hcAcQ/

You need to escape the backslash before the . 您需要在之前转义反斜杠. , I believe: , 我相信:

^[0-9]+(\\.[0-9][0-9])$

The reason that a 4 digit (or greater) number will work is because the single backslash isn't actually escaping that . 使用4位数(或更大位数)的数字的原因是因为单个反斜杠实际上并未对此进行转义. to be a period character, thus causing it to act as the wildcard " match any character " dot. 成为句点字符,从而使其充当通配符“ 匹配任何字符 ”点。

When you have 3 or fewer digits this fails because there aren't enough characters for every match in the regex, but the with 4 digits it will work (one digit for the first character class, one for the . , and one each for the other two character classes. 当您有3个或更少的数字时,此操作将失败,因为正则表达式中的每个匹配项都没有足够的字符,但是4个数字将起作用(第一个字符类为一个数字,。个为一个字符,第一个为一个字符类) .其他两个字符类。

Escaping the \\ will cause the . 转义\\将导致. to actually be interpreted as a literal . 实际上被解释为文字. character, as you probably intended. 字符,正如您可能想要的那样。 You could also instead define your variable as a regex literal (MDN example; near the top) so that you don't have to deal with escaping \\ characters within the string: 您还可以改为将变量定义为正则表达式文字(MDN示例;在顶部附近),这样就不必处理字符串中的转义\\字符:

//instead of new valueFormat = new RegExp('^[0-9]+(\\.[0-9])$');
valueFormat = /^[0-9]+\.[0-9][0-9]$/;

This works(\\. instead of .): 这适用于(\\。而不是。):

// valueFormat = new RegExp('^([0-9]+)(\.[0-9][0-9])$');    
valueFormat = new RegExp('^([0-9]+)(\\.[0-9][0-9])$');

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

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