Forum: Ruby Easy way to escape text for use in regexps?

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.
Bb4bdf2b184027bc38d4fb529770cde5?d=identicon&s=25 Wes Gamble (weyus)
on 2006-05-02 20:45
I need to be able to include some arbitrary text as input into a regular
expression and I'm looking for a way to escape regular expression
metacharacters within my data(e.g. escape a "?" for example).

Is there a library somewhere that has this function available?

Thanks,
Wes
Bb4bdf2b184027bc38d4fb529770cde5?d=identicon&s=25 Wes Gamble (weyus)
on 2006-05-02 20:47
Sorry all.

I'll look harder next time.

How embarrassing.

Regexp.escape()

Thanks,
Wes


Wes Gamble wrote:
> I need to be able to include some arbitrary text as input into a regular
> expression and I'm looking for a way to escape regular expression
> metacharacters within my data(e.g. escape a "?" for example).
>
> Is there a library somewhere that has this function available?
>
> Thanks,
> Wes
9358cc96c46055cd68d4a76a9aefe026?d=identicon&s=25 Daniel Harple (Guest)
on 2006-05-03 19:00
(Received via mailing list)
On May 2, 2006, at 8:45 PM, Wes Gamble wrote:

> I need to be able to include some arbitrary text as input into a
> regular
> expression and I'm looking for a way to escape regular expression
> metacharacters within my data(e.g. escape a "?" for example).

$ ri Regexp::escape
--------------------------------------------------------- Regexp::escape
      Regexp.escape(str)   => a_str
      Regexp.quote(str)    => a_str
------------------------------------------------------------------------
      Escapes any characters that would have special meaning in a
      regular expression. Returns a new escaped string, or self if no
      characters are escaped. For any string, Regexp.escape(str)=~str
      will be true.

         Regexp.escape('\*?{}.')   #=> \\*\?\{\}\.
This topic is locked and can not be replied to.