Regexp: why does (re)* return only last repetition?

Hi –

From: dblack@superlink.net
To: “ruby-talk ML” ruby-talk@ruby-lang.org
Sent: Tuesday, May 13, 2003 1:21 PM
Subject: Re: Regexp: why does (re)* return only last repetition?

I’m not sure what you mean by “interpolate again” (or reinterpolate).
I think everything is happening just once: you’ve created a string
([a-z]), and you’re interpolating it into a regex.

Frankly, /#{a}/ for the above string should be no different than
/[a-z\]/.

Except… a is a 6-char string ([a-z]), and the contents of the regex
there is 7 characters :slight_smile: There’s no way for Ruby to backtrack and
know that, when you created the string, you typed \ twice. You might
have produced the string this way:

a = [91, 97, 45, 122, 92, 93].map {|c| c.chr}.join # [a-z]

I think what he wants is reasonable in a way…
it would be nice if there were a way to specify
a string (or a regex) that did not expand
backslashes. If there were, that would solve his
minor dilemma.

“Interpolate” is not the right word here… but
there are definitely two levels of processing
going on. For example: The sequence of characters
“\\n” gets mapped internally to “\n” and if that
in turn were used in a regex, it would be collpsed
again into \n. Correct?

I don’t think so:

irb(main):016:0> a = “\\n”
=> “\\n”
irb(main):017:0> puts a
\n
=> nil
irb(main):018:0> /#{a}/
=> /\n/
irb(main):019:0> /#{a}/.match(“\n”)
=> nil

Once you create the string (in this case the 3-char string \n), it
just gets dropped into the #{} expression as is. (If you eval’d it
you could force an extra level of processing.)

What about a naive solution like this?

class String
def raw
self.inspect[1…-2]
end
end

And then /#{myvar.raw}/ or some such. Am I way
off base here? This is untested. :slight_smile:

Tricky :slight_smile: You might run aground on interpolating things other than
strings; you’d have to define Kernel#raw (as to_s.raw or maybe
to_str.raw). And even then, well, I’m not sure… :slight_smile:

David

···

On Wed, 14 May 2003, Hal E. Fulton wrote:

----- Original Message -----


David Alan Black
home: dblack@superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav