Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract a substring from string using a regular expression?

Tags:

regex

ruby

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?

like image 952
Alex Avatar asked Apr 27 '11 10:04

Alex


2 Answers

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

like image 129
Sector Avatar answered Sep 19 '22 22:09

Sector


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
like image 24
fl00r Avatar answered Sep 20 '22 22:09

fl00r