Yogzzz
Yogzzz

Reputation: 2785

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?

Upvotes: 0

Views: 445

Answers (3)

Damon Aw
Damon Aw

Reputation: 4792

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 (e.g. a hand typed one www.mydomain.com/image333.png without a scheme, the path and host will be undefined too.

Upvotes: 0

Lee Jarvis
Lee Jarvis

Reputation: 16241

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"

Upvotes: 0

Erez Rabih
Erez Rabih

Reputation: 15788

"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

Upvotes: 1

Related Questions