简体   繁体   中英

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

SHOULD PASS 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

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.

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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