Regexp grouping question

P

petermichaux

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
 
C

Chris Alfeld

compressed =3D "foo =3D bar; red =3D herring;"
compressed =3D compressed.gsub(/\s*([=3D;])\s*/,'\1')

I believe #$1 is evalued *before* gsub is executed and hence fails.=20
gsub sets the variable and uses \1, \2, \3 in the replacement string
to correspond.
 
P

petermichaux

Chris said:
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
 
L

Logan Capaldo

Chris said:
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

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

compressed.gsub(regexp) { |matched_string| $1 }
 
D

David Drub

unknown said:
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;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top