Partial GSUB match / replacement

I need to match a somewhat complicated match using gsub, then modify
part of it, leaving the rest intact

for example, replacing
“url(http://www.google.com)”
with
“url(HTTP://WWW.GOOGLE.COM)”

this is the closest answer I can come up with
gsub /(url([‘"]?)([^)’“]+)(['”]?))/, “\1#{”\2".capitalize}\3"
or
gsub /(url([‘"]?)([^)’“]+)(['”]?))/, “\1\2.capitalize\3”
but neither of these solutions work

It doen’t have to be with gsub, I just thought this would be the most
straightforward way

ideas?

thanks

On Sun, Nov 21, 2010 at 1:04 AM, Shea B. [email protected] wrote:

or
gsub /(url([‘"]?)([^)’“]+)(['”]?))/, “\1\2.capitalize\3”
but neither of these solutions work

It doen’t have to be with gsub, I just thought this would be the most
straightforward way

ideas?

You can use a block with gsub, where the back-references are
accessible via the $1, $2, etc:

“url(http://www.google.com)”.gsub(/(url([‘"]?)([^)’“]+)(['”]?))/)
{“#{$1}#{$2.upcase}#{$3}”}
=> “url(HTTP://WWW.GOOGLE.COM)”

Note that I replaced #capitalize with #upcase to upcase all characters
not just the first one.

HTH,
Ammar

You can use following regexp:
string.gsub!(/(url([‘“]?)(.+?)([”’]?))/) { “#{$1}#{$2.upcase}#{$3}” }

It is similar to yours with two differences:

  1. I’m using (.+?)
    question mark here means that + is no longer greedy, it will match only
    to the point where next element in regexp is detected: and in your case
    that is either ", ’ or )

  2. You cannot use functions on references like “\2.capitalize” or
    “\2”.capitalize. It is just enterpreted as string. If you want to get
    matches as actual string representations, you should use a block.

[class String - RDoc Documentation]

hope this helps :slight_smile:

Thanks a bunch

Although the last example by w_a_x_man looks efficient and simpler, I
needed a very specific match, as it actually matching
(http://www.google.com) and not even considering the url, then just
trying to capitalize the parentheses.

I went with
“url(http://www.google.com)”.sub /(url([‘"]?)([^)’“]+)(['”]?))/,
“#{$1}#{$2.upcase}#{$3}”

Actually I’m having a bit more trouble.

When I use css.gsub /(url([’"]?)([^)’"]+)([’"]?))/,
“#{$1}#{$2.upcase}#{$3}”

on a block of css, what happens is, every instance of url(…), gets
replaced with the upcase of the last instance of it.

so
body {
background: url(/images/site_background.png)
}
p {
background: url(/images/image.png);
margin-left: 10px;
}
=>
body {
background: url(/IMAGES/IMAGE.PNG)
}
p {
background: url(/IMAGES/IMAGE.PNG);
margin-left: 10px;
}

On Nov 20, 5:04pm, Shea B. [email protected] wrote:

or

Posted viahttp://www.ruby-forum.com/.

“url(http://www.google.com)”.sub( /(.*?)/ ){|s| s.upcase}
==>“url(HTTP://WWW.GOOGLE.COM)”

My bad. had to put the replacement string in a block

css.gsub(/(url([’"]?)([^)’"]+)([’"]?))/) {"#{$1}#{$2.upcase}#{$3}"}