简体   繁体   English

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

[英]Regular expression to allow comma and space delimited number list

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!!! 我尝试下面的代码他们似乎工作,但当我输入3a作为数字,它通过! How? 怎么样? I cannot understand how my code allowed that letter to pass. 我无法理解我的代码如何允许该字母通过。

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

正则表达式^[\\d,\\s]+$不会这样做吗?

试试这个Regex ... 点击查看你的演示

^[0-9 _ ,]*$

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). 它不会处理所有事情,比如在没有数字的逗号(如果这是你想要的)之间失败。

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

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