Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regular expression for version numbers

I want to write a program which takes build number in the format of 23.0.23.345 (first two-digits then dot, then zero, then dot, then two-digits, dot, three-digits):

number=23.0.23.345
pattern = /(^[0-9]+\.{0}\.[0-9]+\.[0-9]$)/

numbers.each do |number| 
    if number.match pattern
        puts "#{number} matches"
    else
        puts "#{number} does not match"
    end
end

Output: I am getting error: floating literal anymore put zero before dot

like image 373
Raghu Veeragandham Avatar asked Dec 14 '25 07:12

Raghu Veeragandham


1 Answers

I'd use something like this to find patterns that match:

number = 'foo 1.2.3.4 23.0.23.345 bar'
build_number = number[/
  \d{2} # two digits
  \. 
  0 
  \. 
  \d{2} # two more digits
  \.
  \d{3}
/x]
build_number # => "23.0.23.345"

This example is using String's [/regex/] method, which is a nice shorthand way to apply and return the result of a regex. It returns the first match only in the form I'm using. Read the documentation for more information and examples.

Your pattern won't work because it doesn't do what you think it does. Here's how I'd read it:

/(       # group
  ^      # start of line
  [0-9]+ # one or more digits
  \.{0}  # *NO* dots
  \.     # one dot
  [0-9]+ # one or more digits
  \.     # one dot
  [0-9]  # one digit
  $      # end of line
)/x

The problem is \.{0} which means you don't want any dots.

The x flag tells Ruby to use multiline, which ignores blanks/whitespace and comments, making it easy to build a pattern that is documented.

like image 165
the Tin Man Avatar answered Dec 16 '25 21:12

the Tin Man



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!