Ruby regex to match only single digits in a comma-

2019-08-05 08:07发布

问题:

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.

回答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).