1
1      #valid
1,5    #valid
1,5,   #invalid
,1,5   #invalid
1,,5   #invalid
       #'nothing' is also invalid

The number of numbers separated by commas can be arbitrary.

I'm trying to use regex to do this. This is what I have tried so far, but none of it worked:

"1,2,," =~ /^[[\d]+[\,]?]+$/      #returned 0
"1,2,," =~ /^[\d\,]+$/            #returned 0
"1,2,," =~ /^[[\d]+[\,]{,1}]+$/   #returned 0
"1,2,," =~ /^[[\d]+\,]+$/         #returned 0

Obviously, I needed the expression to recognize that 1,2,, is invalid, but they all returned 0 :(

bli00
  • 2,215
  • 2
  • 19
  • 46

1 Answers1

3

Your patternsare not really working because:

  • ^[[\d]+[\,]?]+$ - matches a line that contains one or more digit, +, ,, ? chars (and matches all the strings above but the last empty one)
  • ^[\d\,]+$ - matches a line that consists of 1+ digits or , symbols
  • ^[[\d]+[\,]{,1}]+$ - matches a line that contains one or more digit, +, ,, { and } chars
  • ^[[\d]+\,]+$ - matches a line that contains one or more digit, +, and , chars.

Basically, the issue is that you try to rely on a character class, while you need a grouping construct, (...).

Comma-separated whole numbers can be validated with

/\A\d+(?:,\d+)*\z/

See the Rubular demo.

Details:

  • \A - start of string
  • \d+ - 1+ digits
  • (?:,\d+)* - zero or more occurrences of:
    • , - a comma
    • \d+ - 1+ digits
  • \z - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • what is the difference between `[]` and `()`? – bli00 Feb 05 '17 at 20:40
  • `[abc]` finds 1 character, either `a`,`b` or `c`. `(abc|def)` will find either a literal char sequence `abc` or `def`. `[...]` are character classes/bracket expressions and `(...)` are grouping constructs. `(?:...)` is a non-capturing group (does not store the part of the match in a separate memory buffer). – Wiktor Stribiżew Feb 05 '17 at 20:51
  • what is `:` in the context of `?:,`? I tried using it like this: `{1}:,` but it didnt work. – bli00 Feb 05 '17 at 20:55
  • Also note that the character class inside a character class makes a union. Thus, `[[\d][^\w]]+` will match 1+ chars that are either digits or chars other than word chars. As for `(?:...)`, I already noted above, that it is a [**non-capturing group**](http://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group-what-does-a-question-mark-followed-by-a-colon). – Wiktor Stribiżew Feb 05 '17 at 20:57