[英]Regex to match if string contains integer/decimal with digits
I want to write a regex that allows an integer number, or a decimal number with 0 - 2 decimal digits. 我想写一个正则表达式,它允许一个整数或带有0-2个十进制数字的十进制数字。
Valid Input 有效输入
1
1.
1.1
1.11
111111111
111111111.
111111111.1
111111111.11
Invalid Input 输入无效
a
a.
1.a
1.111
1.1111
Here is the regex I came up with 这是我想出的正则表达式
\d*\.?([\d]){0,2}
I am having trouble testing it to ensure it works. 我无法对其进行测试以确保其正常工作。 I found a couple ways of testing it.
我发现了几种测试方法。 Using the
test
method which I just used w3schools setup here . 使用我刚才在这里使用w3schools设置的
test
方法。 The other way was with some javascript regular expression tester like regexr and regex101 . 另一种方法是使用某些javascript正则表达式测试器,例如regexr和regex101 。 For all of these: it appears that either my regular expression is returning false positives, or my regular expression does not work as intended.
对于所有这些情况:看来我的正则表达式返回了误报,或者我的正则表达式无法正常工作。
Question : What regex would do what I want it to do? 问题 :什么正则表达式可以做我想要做的事情?
^...$
^...$
检查完整的字符串(从第一个字符到最后一个字符) ^...$
+
and not *
). +
而不是*
)。 Check this example: 检查以下示例:
r = /^\\d+\\.?\\d{0,2}$/ tests = ['1', '1.', '1.1', '1.11', '111111111', '111111111.', '111111111.1', '111111111.11', 'a', 'a.', '1.a', '1.111', '1.1111'] tests.forEach(function(val) { console.log(val, val.match(r) ? ': valid' : ': invalid'); });
Following the comments - if you need a solution for "integer number, or a decimal number with 0 - 2 decimal digits" (like you said in the question, but not like the valid input section), you can use this: 在注释之后-如果您需要“整数或具有0-2个十进制数字的十进制数字”的解决方案(就像您在问题中说的那样,但不喜欢有效的输入部分),则可以使用以下方法:
r = /^\\d+(\\.\\d\\d{0,1})?$/ console.log('1.'.match(r)) tests = ['1', '1.', '1.1', '1.11', '111111111', '111111111.', '111111111.1', '111111111.11', 'a', 'a.', '1.a', '1.111', '1.1111'] tests.forEach(function(val) { console.log(val, val.match(r) ? ': valid' : ': invalid'); });
Don't forget closing and opening in Regex, many new Regex for get it and they end up unwanted result, everything should between ^ and $, ^ is starting point of the word(digit) boundary and $ is ending point...something like below should help you, try: 不要忘了在正则表达式中关闭和打开,许多新的正则表达式都得到了它,并且它们最终导致不必要的结果,所有内容都应介于^和$之间,^是字(数字)边界的起点,而$是终点...如下所示应该可以帮助您,请尝试:
'use strict';
var decimal = /^\d+(\.\d\d{0,2})$/, num = 111111111.11;
console.log(decimal.test(num));
Hope this helps... 希望这可以帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.