简体   繁体   中英

Rails Regular Expression

I'm really new to regular expression. I have the following url: http://www.foo.bar.com/hgur_300x300.jpg and http://www.foo.bar.com/hgur_100x100.jpg

How would I use gsub with regular expression in rails to find [300X300.jpg AND 180X180.jpg] and replace it with 500X500?

"http://www.foo.bar.com/hgur_100x100.jpg".gsub(/\d+/, "500")

will replace the two "100" with "500"

UPDATE:

"http://www.foo.bar.com/hgur_100x100.jpg".gsub(/\d+x\d+/, "500x500")

will be more precise

Please don't you a regular expression on the entire URL. URLs should be uniform, expressions can easily break them. You should split the path away from the rest of it first, then have a somewhat strict expression.

This code will use Rubys uri library to parse and then modify the path directly.

uri = URI.parse("http://www.foo.bar.com/hgur_300x300.jpg")
uri.path #=> "/hgur_300x300.jpg"
uri.path.gsub!(/\d{3}/, '500')
uri.to_s #=> "http://www.foo.bar.com/hgur_500x500.jpg"

I suggest using the following method.

If your URL is a pure string, then just "my_url.com/hgur_100x100.jpg".gsub(/\\d+x\\d+/,"500x500") .

This will match "100x100" and you replace it "500x500"

I'm suggesting this because if you just match using \\d+/ , you end up matching all numbers in the URL, including port numbers.

@injekt's method of using URI.path is pretty good. I've been using URI and I think it's a pretty solid module. But that is very dependent on you having well-formed URIs in the first place. For example, if you punch in a URL (eg a hand typed one www.mydomain.com/image333.png without a scheme , the path and host will be undefined too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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