Equivalent of perl's \Q in regexps?

marker = ‘***’

code = <<-EOT
var x = 1
//*** hello
function foo() {}
EOT

p code.to_a.grep(/***/) # -> ["//*** hello\n"] that’s what
I
want but using marker

#p code.to_a.grep(/#{marker}/) # -> invalid regexp error

p code.to_a.grep(/#{%q(marker)}/) # -> [], doesn’t work

In perl you can do /\Q$marker/ and it escapes $marker for the regexp.

Simon.

On 7/28/06, Simon B. [email protected] wrote:

want but using marker
Simon.


Simon B. [email protected]

Maybe you want %r:

regex = %r{^\s*[a-z]}

On Jul 27, 2006, at 9:10 PM, Simon B. wrote:

want but using marker
Simon.

Just guessing but I believe you want
/#{Regexp.escape(marker)}/

or Regexp.new(Regexp.escape(marker))

On 7/28/06, Daniel B. [email protected] wrote:

Maybe you want %r:

regex = %r{^\s*[a-z]}

No no, silly me that won’t help… you’d still have to escape the
regex-special chars. Logan’s got a better answer :slight_smile:

;D

On 7/28/06, Logan C. [email protected] wrote:

EOT

In perl you can do /\Q$marker/ and it escapes $marker for the regexp.

Just guessing but I believe you want
/#{Regexp.escape(marker)}/

or Regexp.new(Regexp.escape(marker))

Cool. It works. Thanks

Not quite as pretty as I’d like. Maybe a %R(…) would be a nice
sweetener.
Simon.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs