0

I am trying to get a regex to check for only numbers and commas so for example

This will go through

1 0,3,4 1,3 1,3,15,12 

This will not go through

abc 1,,3,,4 1,3, ,1,1 

My current regex is

/[0-9]*[,][0-9]*/ 

it doesnt seem to work as what i wanted Can i get some help thanks

1
  • what is your desired output? Commented Mar 5, 2018 at 15:21

5 Answers 5

2

You can use a regex like this:

^\d+(,\d+)*$ 

Working demo

Sign up to request clarification or add additional context in comments.

3 Comments

Did you forget a * at the end? This will match 1,22 and not 1,2,3.
@Onyambu as far as I understood value 1,22 is a correct match
You have editted it. Before the edition the regex could not be able to match 1,2,3..but now it can match because of the *
1

Use this Regex ^([0-9]+,)*[0-9]+$

var re = new RegExp('^([0-9]+,)*[0-9]+$'); function check(){ var str=$('#hi').val(); console.log(str); if(str.match(re)) $('#result').html("Correct"); else $('#result').html("InCorrect"); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="hi"> <button onclick="check()">Check</button> <p id="result"></p>

2 Comments

Thank you very much
I'm glad I could help. @DragonKnight
1

Regex: ^\d+(?:,\d+)*$

var array = ['1', '0,3,4', 'abc', '1,,3,,4', '1,3,', ',1,1']; for (var i of array) { console.log(i + ' => ' + /^\d+(?:,\d+)*$/g.test(i)) }

Comments

0

This isn't Regex, but here is a way to do it:

// Your test input values (which I will assume are strings for this code): /* * 1 * 0,3,4 * 1,3 * 1,3,15,12 */ const str = '1,3,15,12'; const isValid = str.split(',') .map((val) => !isNaN(parseInt(val))) .reduce((currentVal, nextVal) => currentVal && nextVal, true); console.log(isValid);

Comments

0

Your current regex: /[0-9]*[,][0-9]*/ will match ,

1,1

,6

4953,5433

5930,

etc.

Assuming you want to match a comma-separated list of numbers (each with any number of digits), You would need: /\d+(,\d+)*/ where \d is shorthand for [0-9]:

/[0-9]+(,[0-9]+)*/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.