Regex to match comma separated numbers or stop (Fu

2019-09-19 16:32发布

This question already has an answer here:

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.

3条回答
叼着烟拽天下
2楼-- · 2019-09-19 17:13

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(',') : []);

查看更多
家丑人穷心不美
3楼-- · 2019-09-19 17:17

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
查看更多
不美不萌又怎样
4楼-- · 2019-09-19 17:18

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

查看更多
登录 后发表回答