1

I'm new to Rails, and furthermore to regex. Been looking around, but I'm blocked...

I have a string like this :

Current: http://zs.domain.com/user_images/123456789/imageName_size.ext

Wanted: http://zs.domain.com/user_images/123456789/imageName.ext

I've managed to get to this :
http://a0.twimg.com/profile/1240267050/logo1.png
=> losing all occurrences with

picture.gsub!(/_([a-z0-9-]+)/, '')

or this :

http://a0.twimg.com/profile_images/1240267050/logo1
=> changing only the last occurrence, but losing the extension with

picture.gsub!(/_([a-z0-9-]+)**.(png|gif|jpg|jpeg)**/, '')  

2 Answers 2

3

You're almost there. The second parameter is the string with which the match will be replaced, and you can re-use matched groups from the match. This will do the trick:

picture.gsub!(/_([a-z0-9-]+).(png|gif|jpg|jpeg)/, '.\2')

To accomodate for the additional conditions, as posed in the comment:

picture.gsub!(/_([^\/]+).(png|gif|jpg|jpeg)/, '.\2')
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much ! Regex is tricky for beginner hackers ;) However, there's another option i didn't realize - the images i'm trying to regex are the twitter profile images. The _size section of the image name (i.e. ImgName_size.ext) can be _small, _normal or _reasonably_small. In the last case it only replaces the _small part...
How about this one (see the updated answer). Also, try not to see regexes as magic. When you have some time, read an article about Finit State Automatons, that will make clearer how the work.
@mark : thank you, starting to understand :) although the second solution give me a syntax error. /home/laurent/Dev/blog/app/views/users/show.html.erb:10: premature end of char-class: /_([^/ /home/laurent/Dev/blog/app/views/users/show.html.erb:10: syntax error, unexpected ']', expecting ')' ...= ( @user.picture.gsub!(/_([^/]+).(png|gif|jpg|jpeg)/,".\2")... ... ^
Oh sorry, you need a \ for the / (fixed in the answer)
This regexp has some problems. See my answer.
0

markijbema's answer will change the string

.../xxx_yyygifzzz/...,

into

.../xxxgifzzz/....

In order to avoid that, you can do this:

picture.gsub!(/_[^\/]+(?=\.[^\.]+\z)/, '')
  • (?=...) is understood as a context that follows the string, and will not be included in the match.
  • \z describes the end of the string, so this regexp is safe to use when some intermediate directory includes a string like above.

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.