Forum: Ruby Regexp grouping question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
unknown (Guest)
on 2006-04-02 01:10
(Received via mailing list)
Hi

I'm trying to remove unecessary white space around equals signs and
after semicolons

compressed = "foo = bar; red  = herring;"
compressed = compressed.gsub(/\s*([=;])\s*/,"#$1")
puts compressed

produces
foobarredherring

but I would like it to produce
foo=bar;red=herring;

Seems like the #$1 is not working. I also tried #{$1} but that didn't
work either.

Any ideas?

Thanks,
Peter
Chris A. (Guest)
on 2006-04-02 01:16
(Received via mailing list)
compressed = "foo = bar; red  = herring;"
compressed = compressed.gsub(/\s*([=;])\s*/,'\1')

I believe #$1 is evalued *before* gsub is executed and hence fails.
gsub sets the variable and uses \1, \2, \3 in the replacement string
to correspond.
unknown (Guest)
on 2006-04-02 01:31
(Received via mailing list)
Chris A. wrote:
> compressed = "foo = bar; red  = herring;"
> compressed = compressed.gsub(/\s*([=;])\s*/,'\1')
>
> I believe #$1 is evalued *before* gsub is executed and hence fails.
> gsub sets the variable and uses \1, \2, \3 in the replacement string
> to correspond.

Thank you!

Peter
Logan C. (Guest)
on 2006-04-02 02:29
(Received via mailing list)
On Apr 1, 2006, at 4:28 PM, removed_email_address@domain.invalid wrote:

>
> Peter
>
>

If you want to use $1, $2, $3, etc. with gsub, you can use the block
form:

compressed.gsub(regexp) { |matched_string| $1 }
Drub D. (Guest)
on 2007-06-23 01:33
unknown wrote:
> Hi
>
> I'm trying to remove unecessary white space around equals signs and
> after semicolons
>
> compressed = "foo = bar; red  = herring;"
> compressed = compressed.gsub(/\s*([=;])\s*/,"#$1")
> puts compressed
>
> produces
> foobarredherring
>
> but I would like it to produce
> foo=bar;red=herring;
>
> Seems like the #$1 is not working. I also tried #{$1} but that didn't
> work either.
>
> Any ideas?
>
> Thanks,
> Peter

This thread has been *very helpful*.  Thank you!

What if the input syntax allows spaces in the field values?

Possible input:
foo =    high bar jump ; red = pickled herring    ;

And, let's remove leading and trailing white space.

Desired results:
foo=high bar jump;red=pickled herring;
This topic is locked and can not be replied to.