Gsup with variable when replacing

Hi people,

I’m trying to transform this kind of line :
123232321
FOOFOOFOO

2431232
BARBARBAR

to
123232321 (actually XML)
2431232
So I have coded this script
File.open(“D:/digisoft/1b.txt”,“r”) do |f2|
while line = f2.gets
f3 = line.gsub!(/\d+$/,’\1’)
puts f3
end
end

but Ruby doesn’t seem to apraciate … I search example and I found
that variable as $1, \1, &$ could do this job but i can’t get it
works.
How can I get the match of my regexp and add blocks please ?

thanks you

Romain LOMBARDO wrote:

f3 = line.gsub!(/\d+$/,’\1’)

\1 means “first group”, but there are no groups in your regex. \0 means
“whole
match”, so that’s the one you want.
Another thing: gsub! is the mutating variant of gsub. It will return nil
when
no change occurs or self when there is a change. Either way it does not
make
sense to store its return value.
And yet another thing: there is no sense in using gsub (as opposed to
sub)
with a regex that only matches once anyway.

HTH,
Sebastian

On Mon Jul 28 21:44:41 2008, Romain LOMBARDO wrote:

123232321 (actually XML)
that variable as $1, \1, &$ could do this job but i can’t get it
works.
How can I get the match of my regexp and add blocks please ?

thanks you

You’re missing the brackets around the \d+, like so:

f3 = line.gsub(/(\d+)$/,’\1’)

Note that I am also using String#gsub not String#gsub! as that will
change your line variable also.

On 28.07.2008 14:51, Sebastian H. wrote:

Romain LOMBARDO wrote:

f3 = line.gsub!(/\d+$/,’\1’)

\1 means “first group”, but there are no groups in your regex. \0 means “whole
match”, so that’s the one you want.

I wasn’t aware that \0 does the job as well. I always use & for the
whole match. Learn something new every day. :slight_smile:

Another thing: gsub! is the mutating variant of gsub. It will return nil when
no change occurs or self when there is a change. Either way it does not make
sense to store its return value.
And yet another thing: there is no sense in using gsub (as opposed to sub)
with a regex that only matches once anyway.

Absolutely.

Another remark, iterating through a file can be made easier:

File.foreach(“D:/digisoft/1b.txt”) do |line|
line.gsub!(/\d+$/,’\&’)
puts line
end

Kind regards

robert

On Jul 28, 5:42 pm, Romain LOMBARDO [email protected] wrote:

123232321 (actually XML)
2431232
So I have coded this script
File.open(“D:/digisoft/1b.txt”,“r”) do |f2|
while line = f2.gets
f3 = line.gsub!(/\d+$/,‘\1’)
puts f3
end
end

while line = f2.gets
print ‘’,line.to_i,‘’,“\n” if line=~/\d/
end

  • I am not sure if this is perfect solution, but this works and prints
    what you expected.

Thanks,
sathyz