# Easy way to escape text for use in regexps?

**URL:** <https://www.ruby-forum.com/t/easy-way-to-escape-text-for-use-in-regexps/94370>\
**Category:** Ruby\
**Created:** [May 2, 2006, 8:45pm UTC](https://www.ruby-forum.com/t/easy-way-to-escape-text-for-use-in-regexps/94370 "2006-05-02T20:45:25Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![weyus](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7ab992/32.png) [@weyus](https://www.ruby-forum.com/u/weyus)\
**Post date:** [May 2, 2006, 8:45pm UTC](https://www.ruby-forum.com/t/easy-way-to-escape-text-for-use-in-regexps/94370/1 "2006-05-02T20:45:25Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![weyus](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7ab992/32.png) [@weyus](https://www.ruby-forum.com/u/weyus)\
**Post date:** [May 2, 2006, 8:47pm UTC](https://www.ruby-forum.com/t/easy-way-to-escape-text-for-use-in-regexps/94370/2 "2006-05-02T20:47:26Z")

</div>

Sorry all.

I’ll look harder next time.

How embarrassing.

Regexp.escape()

Thanks,  
Wes

Wes G. 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

---

<div class="post-metadata">

**Author:** ![weyus](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7ab992/32.png) [@weyus](https://www.ruby-forum.com/u/weyus)\
**Post date:** [May 3, 2006, 7:00pm UTC](https://www.ruby-forum.com/t/easy-way-to-escape-text-for-use-in-regexps/94370/3 "2006-05-03T19:00:43Z")

</div>

On May 2, 2006, at 8:45 PM, Wes G. 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('\*?{}.') #=> \\*\?\{\}\.
```
