简体   繁体   English

Rails 3 +正则表达式-替换字符串的一部分,出现1次

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

I'm new to Rails, and furthermore to regex. 我是Rails和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 当前:http: http://zs.domain.com/user_images/123456789/imageName_size.ext

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

I've managed to get to this : 我已经设法做到这一点:
http://a0.twimg.com/profile/1240267050/logo1.png 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 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 markijbema的答案将更改字符串

.../xxx_yyygifzzz/... , .../xxx_yyygifzzz/...

into

.../xxxgifzzz/... . .../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. \\z描述了字符串的结尾,因此当某些中间目录包含上述字符串时,可以安全地使用此regexp。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM