Regular expression to allow comma and space delimited number list
Asked Answered
P

3

9

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!!!');
Patmos answered 4/7, 2013 at 14:15 Comment(3)
[\d] is exactly the same as just \d without the []Lederhosen
Also the answer to your question is that you're leaving off $ at the end of the regular expression, which means that the matched pattern may be followed by any subsequent characters.Lederhosen
Your test case above will only be testing the final regex.Kat
K
10

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

Kat answered 4/7, 2013 at 14:17 Comment(5)
You need a * or a +, and multiple commas in sequence might be undesirableLederhosen
Yup, just tested it and came to the same conclusion.Kat
but I tested /^[\d\s,]*/ and it still allows 3a because it sees 3. It is not rejecting 3a. it is so strange.Patmos
@Patmos no, that regex will not match "3a". You're still forgetting the $ at the end of the pattern!Lederhosen
thank you , you are right, it seems to be working. let me test it and get back to you. Thank you all for your quick replies.Patmos
P
1

Try this Regex... Click to view your demo

^[0-9 _ ,]*$
Polymath answered 4/7, 2013 at 14:20 Comment(0)
I
0

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

Incompetence answered 4/7, 2013 at 14:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.