Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match list of numbers

Tags:

regex

I'm trying to write a regex to match a very long list of numbers separated by commas and an optional space. It can't match a single integer. The list of numbers is approx 7000 bytes long bounded by text on either side.

12345 => don't match
12345,23456,34567,45678 => match
12345, 23456, 34567, 45678 => match

My current regex,

(?<!\.)(([0-9]+,)+[0-9]+)(?!\.)

causes a stack overflow. A few I have tried so far are:

([0-9,]+) => doesn't match with optional spaces
((\d+,[ ]?)+\d+) => worse than the original
[ ]([0-9, ]+)[ ] => can't be certain the numbers will be bounded by spaces

I'm using https://regex101.com/ to test the number of steps each regex takes, the original is approx 3000 steps.

Example (elided) string:

Processing 145363,145386,145395,145422,145463,145486 from batch 59

Any help would be appreciated.

like image 553
lhoworko Avatar asked Dec 05 '25 06:12

lhoworko


1 Answers

You can use this regex:

^\d+(?:[ \t]*,[ \t]*\d+)+$

RegEx Demo

  • \d+ matches 1 or more digits
  • (?:...)+ matches 1 or more of following numbers separated by comma optionally surrounded with space/tab.

If you wanted to modify it so a single number is accepted as well, change the (?:...)+ to (?:...)*, like so:

^\d+(?:[ \t]*,[ \t]*\d+)*$
like image 87
anubhava Avatar answered Dec 07 '25 19:12

anubhava