Reputation: 6552
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
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
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.
Upvotes: 1
Views: 800
Reputation: 626851
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.
Upvotes: 1
Reputation: 174706
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"]]
Upvotes: 2