user1788294
user1788294

Reputation: 1893

Change url in a string if present

Sorry I am new to regex so please forgive me . I have several strings such as

"mso-table-lspace:0;mso-table-rspace:0;margin:0;padding:0;background: url(http://someurl/lib/id/w/download_bg.jpg) no-repeat top left #f9f9f9; text-align:center;"

"font-size: 3px; line-height: 3px;"

I want to first check if string contains a image url ( which contains https? and .png or .jpeg or .jpg) and if present in string replace it with a different url.

So for first string the output should be

"mso-table-lspace:0;mso-table-rspace:0;margin:0;padding:0;background: url(http://someotherurl/lib/id/w/download_bg.jpg) no-repeat top left #f9f9f9; text-align:center;"

Upvotes: 0

Views: 73

Answers (4)

Uri Agassi
Uri Agassi

Reputation: 37409

Since your input is CSS, I think it would be pretty safe to assume you are looking for something of this form

url(<http or https>://<some url>/<some path>.<image extension>)

for this, a simplified regex (not needing the complicated regex for actually trying to match URL, and might be very non-trivial) could be used:

text.gsub(%r{(url\(https?://)[^/]+/([^\)]+\.(png|jpeg|jpg))\)}, '\1someotherurl/\2')
# => "mso-table-lspace:0;mso-table-rspace:0;margin:0;padding:0;
#     background: url(http://someotherurl/lib/id/w/download_bg.jpg no-repeat 
#     top left #f9f9f9; text-align:center;" 

Upvotes: 1

vks
vks

Reputation: 67968

(?=.*?(?:http|https):\/\/.*\/.*?\.(?:jpg|png|jpeg).*)(.*?)https?:\/\/.*\/.*?\)(.*)

Try this.This works for all the cases.

See demo.

http://regex101.com/r/kJ6rS7/1

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

You could try the below gsub command,

gsub(/^(.*?https?:\/\/)([^\/]*)(.*?(?:\.png|\.jpeg|\.jpg))/, '\1someotherurl\3')

Code:

> IO.write("/path/to/the/file", File.open("/path/to/the/file") {|f| f.read.gsub(/^(.*?https?:\/\/)([^\/]*)(.*?(?:\.png|\.jpeg|\.jpg))/, '\1someotherurl\3')})
=> 201

Example:

irb(main):006:0> "mso-table-lspace:0;mso-table-rspace:0;margin:0;padding:0;background: url(http://someurl/lib/id/w/download_bg.jpg) no-repeat top left #f9f9f9; text-align:center;".gsub(/^(.*?https?:\/\/)([^\/]*)(.*?(?:\.png|\.jpeg|\.jpg))/, '\1someotherurl\3')
=> "mso-table-lspace:0;mso-table-rspace:0;margin:0;padding:0;background: url(http://someotherurl/lib/id/w/download_bg.jpg) no-repeat top left #f9f9f9; text-align:center;"

Upvotes: 1

shivam
shivam

Reputation: 16506

It can be done in many ways, one simple example

a = "mso-table-lspace:0;mso-table-rspace:0;margin:0;padding:0;background: url(http://someurl/lib/id/w/download_bg.jpg) no-repeat top left #f9f9f9; text-align:center;"

Now,

a.gsub(a.scan(/http(.*?)(jpg|png)/)[0][0],"://someother-url") if  a.scan(/http(.*?)(jpg|png)/).size > 0
# => "mso-table-lspace:0;mso-table-rspace:0;margin:0;padding:0;background: url(http://someother-urljpg) no-repeat top left #f9f9f9; text-align:center;"

Upvotes: -1

Related Questions