1

I am having input strings like:

"1,7"
"1,2,3, 8,10"
"1, 4,5,7"

I am trying to write a regex to match the above strings with following constraints are:

  • it should match only single digits and that too in range of 1-7
  • the comma after a digit is optional for e.g. there can be a string "4" in which 4 should be matched
  • a digit can be prefixed with whitespace, however it should be ignored

I tried with following:

 ([1-7]),?

but that matches consecutive digits like "55," in following input string and in the same string it also matches "1" in "10," which is incorrect.

 "5,6,7, 55, 8, 10,3"

Considering above input string the desired regex should match 5, 6, 7 and 3.

Note: I am using Ruby 2.2.1

Thanks.

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

1 Answers1

1

You can try the following regular expression:

(?<=^|,|\b)[1-7](?=$|,|\b)

This means a digit [1-7] that must be immediately after a start of string or comma or a word boundary (?<=^|,|\b). And that must be immediately before an end of string or comma or word boundary (?=$|,|\b).

JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
  • I ran your regex in rubular against string `5,6,7, 55, 8, 10,3` and found it not to perform expected matches. It matches "5," , "6," , "7," , " 55" , "1" and "3". The correct matches should be "5", "6", "7" and "3". – Jignesh Gohel Apr 10 '15 at 23:32
  • can you please explain how your regex works by breaking it into pieces like you did earlier? That would help me enhance my regex knowledge as well as others who end-up on reading this answer. – Jignesh Gohel Apr 10 '15 at 23:47