Forum: Ruby Substituting with a find counter . . .

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.
B58c6eef325656d513d26e2c3ae6bfd9?d=identicon&s=25 Peter Bailey (peterbailey)
on 2006-05-23 16:01
In this gsub block, I'd like to save the searched parenthetical data,
indicated by (.*) in line 2. The script works, but, instead of getting
the parenthetical data, I'm getting "$1." Very literal, but, not what I
want. What am I doing wrong?

Thanks.
Peter


1 counter = 0
2  contents.gsub!(/^%%Page:(.*)[0-9]{1,5}$/)  do |match|
3  counter += 1
4  "%%Page: $1 #{counter}"
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2006-05-23 16:16
(Received via mailing list)
2006/5/23, Peter Bailey <pbailey@bna.com>:
> In this gsub block, I'd like to save the searched parenthetical data,
> indicated by (.*) in line 2. The script works, but, instead of getting
> the parenthetical data, I'm getting "$1." Very literal, but, not what I
> want. What am I doing wrong?

You're missing a hash which leads to your $1 being used literally:

> 1 counter = 0
> 2  contents.gsub!(/^%%Page:(.*)[0-9]{1,5}$/)  do |match|
> 3  counter += 1
> 4  "%%Page: $1 #{counter}"

make that last line

"%%Page: #$1 #{counter}"

Kind regards

robert
10d4acbfdaccb4eee687a428ca00a5d8?d=identicon&s=25 Jim Weirich (weirich)
on 2006-05-23 16:23
Peter Bailey wrote:
> In this gsub block, I'd like to save the searched parenthetical data,
> indicated by (.*) in line 2. The script works, but, instead of getting
> the parenthetical data, I'm getting "$1." Very literal, but, not what I
> want. What am I doing wrong?
>
> Thanks.
> Peter
>
>
> 1 counter = 0
> 2  contents.gsub!(/^%%Page:(.*)[0-9]{1,5}$/)  do |match|
> 3  counter += 1
> 4  "%%Page: $1 #{counter}"

"%%Page: #{$1} #{counter}"

should help.

Also, the .* is gobbling up any digits except the last.  You probably
want a space between .* and [0-9], or make the . match non-greedy with
.*?.  Since your replacement string has a space, I'm guessing that's
what you want.

-- Jim Weirich
This topic is locked and can not be replied to.