7

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?

2
  • match returns MatchData and "mtch[0] is equivalent to the special variable $&, and returns the entire matched string. mtch[1], mtch[2], and so on return the values of the matched backreferences" - ruby-doc.org/core/classes/MatchData.html Commented Apr 27, 2011 at 11:25
  • Your link is broken. It's better to show here what you wanted to show. Commented Apr 27, 2011 at 15:47

5 Answers 5

14
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

Sign up to request clarification or add additional context in comments.

Comments

3
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

Comments

2

Without Regexp as an example of another way to do it

url="http://www.site.com/media/pool/product_color_purple.jpg"
color = url[url.rindex("_")+1..-1].split(".")[0]

For this I would stick with regexp though.

color = url.match(/.*_(.*)\./)[1]

Comments

0
>> s = %w(http://www.site.com/media/pool/product_color_purple.jpg http://www.site.com/media/pool/product_color_prince_purple.jpg) 
#=> ["http://www.site.com/media/pool/product_color_purple.jpg", "http://www.site.com/media/pool/product_color_prince_purple.jpg"]
>> s.map { |c| c.match(/\w*_color_(\w+).jpg/)[1] } 
#=> ["purple", "prince_purple"]

Comments

0

You can try this regex.

/color_(.*)?.jpg/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.