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.

2
  • /^[1-5]\|[1-7](\s*,\s*[1-7])*/, perhaps? Commented Apr 13, 2015 at 7:54
  • you mean this ^([1-5])\|\s*([1-7]\s*(?:,\s*[1-7]\s*)*)$ ? Commented Apr 13, 2015 at 7:57

2 Answers 2

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"]]
Sign up to request clarification or add additional context in comments.

1 Comment

is op wants to deal with a single space? then this ^([1-5])\|([1-7] ?(?:, ?[1-7])*)\b$
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.

8 Comments

This will match 2| and its because of that you putted the \s within character class!
@stribizhev add a space after pipe.
I have fixed the regex, now, it should work as expected.
This one matches: ^[1-5]\|(?:(?:[1-7]\s*,\s*)+\s*[1-7]?|[1-7])$
No it will match 2|3,3 , ;) and 2,2,2
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.