Jignesh Gohel
Jignesh Gohel

Reputation: 6552

Ruby regex to match a pattern followed by another pattern

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

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.

Upvotes: 1

Views: 800

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

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

Avinash Raj
Avinash Raj

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

Related Questions