0

I am trying to match comma separated numbers, but if any of the numbers is not valid stop regex and don't match it at all.

Here is an example that should be matched

3123123213212,3123123263212,3173123213212

This string shouldn't be matched

3123123213212,3123123263212dad,3173123213212

So at least one invalid number should lead to unmatched regex.

What I've tried is the following expression

(?:(\d+)(?=\,|\s|$))+

Here is Regex101 link

https://regex101.com/r/JpuA5X/1

The problem that even if some number is invalid it matches other numbers, but this is not acceptable.

How can I modify my regex to get desired result ?

Thanks.

UPDATE

Sorry, I haven't mentioned, I need to group every single number.

  • Why not use a good Tim's regex and then - if a test returns true - split with `,`? You cannot get arbitrary number of groups using just one capturing group in the pattern. – Wiktor Stribiżew Jun 05 '17 at 21:41
  • What do you mean you need to group every single number? What are you expecting as the output result? – KevBot Jun 06 '17 at 15:51

3 Answers3

6

You don't need lookarounds for this. Anchors are sufficient:

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

Explanation:

^     # Start of string
\d+   # Match an integer number
(?:   # Start of non-capturing group
 ,    # Match a comma
 \d+  # Match an integer number
)*    # Repeat group any number of times (including 0)
$     # End of string
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Sorry, I forgot to mention, that I need to group every single number. –  Jun 05 '17 at 17:24
  • 1
    You can't do that in a single regex, at least not in JavaScript. You need to do it in two steps - first, make sure the overall string is valid using above regex, then extract all the numbers using `/\d+/g`. – Tim Pietzcker Jun 05 '17 at 19:33
2

You could look for start and end and the parts between.

var regex = /^(\d+,)*\d+$/;

console.log('3123123213212,3123123263212,3173123213212'.match(regex));
console.log('3123123213212,3123123263212abc,3173123213212'.match(regex));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Sorry, I forgot to mention, that I need to group every single number. –  Jun 05 '17 at 17:21
0

In this instance, I'm not sure it's possible to match and capture what you want without including some other (undesirable) captures, ones that would include the comma.

Instead you can test the string, and if it matches, split the string into an array using the comma as the delimiter. If the string doesn't match, return an empty array or some other value that you would like to symbolize "no match".

var regex = /^\d+(,\d+)*$/;
var valid_string = '3123123213212,3123123263212,3173123213212';
var invalid_string = '3123123213212,3123123263212dad,3173123213212';

console.log(regex.test(valid_string) ? valid_string.split(',') : []);
console.log(regex.test(invalid_string) ? invalid_string.split(',') : []);
Shammel Lee
  • 4,092
  • 1
  • 17
  • 20