javascript 正则表达式允许逗号和空格分隔的数字列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17472580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:27:25  来源:igfitidea点击:

Regular expression to allow comma and space delimited number list

javascriptjqueryregexnumbersdelimited

提问by javafun

I want to write a regular expression using javascript or jquery to allow comma delimited list of numbers OR space delimited numbers OR comma followed by a space delimited numbers OR a combination of any of the above ex anything that is not a digit, space or comma must be rejected

我想使用 javascript 或 jquery 编写一个正则表达式,以允许逗号分隔的数字列表或空格分隔的数字或逗号后跟空格分隔的数字或上述任何非数字、空格或逗号的组合必须被拒绝

SHOULD PASS 111,222,333 111 222 333 111, 222, 333 111,222,333 444 555 666, 111, 222, 333,

应通过 111,222,333 111 222 333 111, 222, 333 111,222,333 444 555 666, 111, 222, 333,

should NOT pass: 111,222,3a 3a 111 222 3a etc etc

不应该通过: 111,222,3a 3a 111 222 3a 等等

I tried the code below they seemed to work however when I typed 3a as a number, it PASSED!!! How? I cannot understand how my code allowed that letter to pass.

我尝试了下面的代码,它们似乎可以工作,但是当我输入 3a 作为数字时,它通过了!!!如何?我无法理解我的代码是如何允许那封信通过的。

I want to reject anything that is not a space, comma or digit

我想拒绝任何不是空格、逗号或数字的内容

or is there a better way to do this without regular expressions? I looked in google and did not find any answer.

或者有没有更好的方法可以在没有正则表达式的情况下做到这一点?我在谷歌上搜索并没有找到任何答案。

Thank you in advance for any help.

预先感谢您的任何帮助。

var isNumeric = /[\d]+([\s]?[,]?[\d])*/.test(userInput);
var isNumeric = /^[\d\s,]*/.test(userInput);    
var isNumeric = /^[\d]*[\s,]*/.test(userInput); 
var isNumeric = /^[\d\s,]*/.test(userInput);    
var isNumeric = /\d+\s*,*/.test(userInput); 

if (isNumeric == false) {
    alert(isNumeric);
  return false;
}
else
      alert('is Numeric!!!');

采纳答案by Grim...

Would the regular expression ^[\d,\s]+$not do the trick?

正则表达式 ^[\d,\s]+$不会起作用吗?

回答by Ganesh Rengarajan

Try this Regex... Click to view your demo

试试这个正则表达式...点击查看您的演示

^[0-9 _ ,]*$

回答by SamWhan

Guess ^(\d+[, ]+)*$should do it.

估计^(\d+[, ]+)*$应该做。

Explanation: A group containing one or more digits followed by at least one space or comma. Group may be repeated any number of times.

解释:包含一个或多个数字后跟至少一个空格或逗号的组。组可以重复任意次数。

It's doesn't handle everything though, like failing when there are commas without a number between (if that's what you want).

但是,它并不能处理所有事情,例如在逗号之间没有数字时失败(如果这是您想要的)。