From: dblack@...
Date: 2003-01-11T06:30:38+09:00
Subject: Re: regexp question
Hi --
On Sat, 11 Jan 2003, Mark Probert wrote:
>
> Hi, again, Rubyists.
>
> Below is code that does multiple substitutions on a block of
> text, using a recursive call to a regexp. The output is like:
>
> s1 = {\aa TEXT:} It is {\bb amazing} what a {\xx regexp} can do
> s2 = TEXT: It is amazing what a
> regexp can do
>
>
> The trouble is I am getting the following warning (repeated 3 times)
>
> warning: string pattern instead of regexp; metacharacters no longer
> effective
>
> when I run the code. The warning comes from the line in the code that reads
>
> s = str.sub(match[0], ssub)
>
> This expression works (no warnings) outside the function. Any ideas as to
> why this is happening and how I can get around the warning?
I couldn't quite get your code to run, and sort of rewrote it (see
below). But in general, that warning has to do with a recent change
in metacharacter handling in cases where an argument can be either a
string or a regex, and I'm pretty sure the warning will only exist for
one version or so of Ruby, and then be taken out.
> BTW, is the a better way of doing this task?
I would use String#gsub:
subs = { "aa" => "alpha",
"bb" => "beta" }
s1 = '{\aa TEXT:} It is {\bb amazing} what a {\xx regexp} can do'
s2 = s1.gsub(/\{\\(\S+)\s([^}]*)\}/) do |s|
tag = subs[$1] || $1
"<#{tag}>#{$2}#{tag}>"
end
puts "s1 = #{s1}"
puts "s2 = #{s2}"
David
--
David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav