开发者

Rails 3 + regex - Replace part of a string, 1 occurrence

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

I have a string like this :

Current: 开发者_StackOverflowhttp://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)**/, '')  


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')


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜