简体   繁体   English

如果字符串包含带数字的整数/小数,则匹配正则表达式

[英]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
  • string allows any number of digit characters, but only allows 1 decimal/period 字符串允许任意数量的数字字符,但仅允许1个小数/句号
  • if a period/decimal exists: only allow 2 digit characters after the decimal 如果存在句点/小数:仅允许小数点后两位数字

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正则表达式测试器,例如regexrregex101 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? 问题 :什么正则表达式可以做我想要做的事情?

  1. You need to make sure that you check the complete string (from the first char to the last char) using ^...$ 您需要确保使用^...$检查完整的字符串(从第一个字符到最后一个字符) ^...$
  2. The first digit should appear at least 1 time (so you want to use + and not * ). 第一位数字应至少出现1次(因此您要使用+而不是* )。

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'); }); 

update 更新

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.

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