I am new to regular expressions in Ruby.
The string looks something like http://www.site.com/media/pool/product_color_purple.jpg
and I am trying to extract from this just the bit which has the colour in it. This can be a variable length, as some of the colours are like prince_purple.jpg
.
So I have:
colour = c.attr('src').match(/(.*)color_(.*).jpg/)
puts "Colour is #{colour}"
What colour returns is the string again, instead of the extracted bit, which is the colour. What is going wrong here?
str="http://www.site.com/media/pool/product_color_purple.jpg"
colour = str.match(/color_([^\/.]*).jpg$/)
puts "Colour is #{colour[1]}"
You not get "Colour is purple" because match returns MatchData, not string
url="http://www.site.com/media/pool/product_color_purple.jpg"
color = url.scan(/color_(.*).jpg/)[0][0]
#=> purple
or
url="http://www.site.com/media/pool/product_color_purple.jpg"
color = url.match(/color_(.*).jpg/)[1]
#=> purple
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With