bli00
bli00

Reputation: 2827

recognize formatted numbers using regex

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 :(

Upvotes: 1

Views: 44

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

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.

Upvotes: 3

Related Questions