Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for repeating series of numbers and number ranges (e.g. 3 digit numbers and 3 digit number ranges)

I'm looking for a regex to match repeating number sequences. The number/range itself could be any three digit number, for e.g. I want to match

345
346-348
234,235,236,237-239
234, 235, 236, 237-239
234,234, 236 and 237-239
234,234, 236 or 237-239

I don't want to match

3454
111-222-333
454,4567 (match only 454)

The number could be any three digit number. I tried different regexs with \d{3} in the mix, but I've not found anything that works. Appreciate any help on this.

like image 910
Bob76 Avatar asked Dec 30 '22 15:12

Bob76


1 Answers

You may use this regex:

^\d{3}(?:-\d{3})?(?:\s*(?:,|and|or)\s*\d{3}(?:-\d{3})?)*(?=,|$)

RegEx Demo

RegEx Details:

  • ^: Start
  • \d{3}: Match 3 digits
  • (?:-\d{3})?: optionally followed by a hyphen and 3 digits
  • (?:: Start non-capture group
    • \s*: Match 0 or more whitespaces
    • (?:,|and|or): Match a comma or and or or
    • \s*: Match 0 or more whitespaces
    • \d{3}: Match 3 digits
    • (?:-\d{3})?: optionally followed by a hyphen and 3 digits
  • )*: Start non-capture group. Repeat this group 0 or more times
  • (?=,|$): Lookahead to assert that we have a comma or End of line ahead of current position
like image 57
anubhava Avatar answered Jan 14 '23 03:01

anubhava