Search code examples
regexregex-groupregex-greedy

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.


Solution

  • With your shown samples, could you please try following.

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

    Online demo for above regex

    Explanation: Adding detailed explanation for above.

    ^\d{3}                   ##Checking from starting of value if value starts from 3 digits.
    (?:                      ##Creating 1st capturing group here.
      -\d{3}$|               ##Matching - followed by 3 digits at end of value OR.
      (?:                    ##Creating 2nd capturing group here.
         (?:,\s*\d{3}\s*){1,3} ##In a non-capturing group matching ,\s* followed by 3 digits with \s* and this whole group 3 times.
         -\d{3}              ##Followed by - 3 digits.
      )|                     ##Closing 2nd capturing group OR.
      (?:                    ##Creating 3rd capturing group here.
         ,\d{3},\s*\d{3}\s*  ##Matching , 3 digits, \s* 3 digits \s*
         (?:and|or)          ##Matching and OR or strings in a non-capturing group here.
         \s*\d{3}-\d{3}      ##Matching \s* followed by 3 digits-3digits
      )?                     ##Closing 3rd capturing group keeping it optional.
    )                        ##Closing 1st capturing group here.
    *(?=,|$)                 ##nd matching its 0 or more matches followed by comma OR end of line.