1

I already have a regex to match only single digits in a comma-delimited string. I need to update it to match the strings like following:

 5|5,4,3
 2|1,2 , 3

The constraints are

  • it should start with a single digit in range of 1-5, followed by a pipe character (|)
  • the string followed by the pipe character - it should be a single digit in range of 1-7, optionally followed by a comma. This pattern can be repetitive. For e.g. following strings are considered to be valid, after the pipe character:

    "6"
    
    "1,7"
    
    "1,2,3, 4,6"
    
    "1, 4,5,7"
    

However following strings are considered to be invalid

    "8"

    "8, 9,10"

I tried with following (a other variations)

  \A[1-5]\|[1-7](?=(,|[1-7]))*

but it doesn't work as expected. For e.g. for sample string

  5|5,4, 3, 10,5

it just matches

  5|5

I need to capture the digit before pipe character and all the matching digits followed by the pipe character. For e.g. in following sample string 5|5,4, 3, 2, 1 the regex should capture

  1. 5
  2. [5, 4, 3, 2, 1]

Note: I am using Ruby 2.2.1

Also do you mind letting me know what mistake I made in my regex pattern which was not making it work as expected?

Thanks.

Community
  • 1
  • 1
Jignesh Gohel
  • 6,236
  • 6
  • 53
  • 89

2 Answers2

2

You could try the below regex.

^([1-5])\|([1-7]\s*(?:,\s*[1-7])*)$

Example:

> "5|5,4, 3, 2, 1".scan(/^([1-5])\|([1-7]\s*(?:,\s*[1-7])*)$/)
=> [["5", "5,4, 3, 2, 1"]]

OR

> "5|5,4, 3, 2, 1".scan(/([1-5])\|([1-7] ?(?:, ?[1-7])*)$/)
=> [["5", "5,4, 3, 2, 1"]]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

You can try the following regex that will match digits and a group of comma/space separated digits after a pipe:

^[1-5]\|(?:(?:[1-7]\s*,\s*)+\s*[1-7]?|[1-7])\b

Here is a demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563