# Escaping special characters :, (, ), \[, \], {, }, !, +, ", ~, ^, -, |, \<, \>, =, \*, ?, \\

**URL:** <https://www.ruby-forum.com/t/escaping-special-characters/126272>\
**Category:** Ferret\
**Created:** [January 16, 2008, 10:05pm UTC](https://www.ruby-forum.com/t/escaping-special-characters/126272 "2008-01-16T22:05:51Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bunny](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3d9bf3/32.png) [@bunny](https://www.ruby-forum.com/u/bunny)\
**Post date:** [January 16, 2008, 10:05pm UTC](https://www.ruby-forum.com/t/escaping-special-characters/126272/1 "2008-01-16T22:05:51Z")

</div>

Hello,

I am trying to escape words for searching i.e., “hello”. The key here  
is that the two L’s on “hello” are actually vertical bars. Is there  
a special function in Ferret or anywhere for that matter that will do  
the escaping of the Ferret special characters?

Thanks in advance,

Benjamin

---

<div class="post-metadata">

**Author:** ![bunny](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3d9bf3/32.png) [@bunny](https://www.ruby-forum.com/u/bunny)\
**Post date:** [January 17, 2008, 12:52am UTC](https://www.ruby-forum.com/t/escaping-special-characters/126272/2 "2008-01-17T00:52:29Z")

</div>

Hello,

I am going to answer my own questions…

You can do something like:

def escape\_string(str)  
str = Regexp.escape(item[:word]).gsub(/([:~!\<\>="])/,’\\\1’)  
end

At one time there was a function called clean\_string in QueryParser  
but it appears to be gone.

Benjamin

---

<div class="post-metadata">

**Author:** ![bunny](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3d9bf3/32.png) [@bunny](https://www.ruby-forum.com/u/bunny)\
**Post date:** [January 17, 2008, 2:19am UTC](https://www.ruby-forum.com/t/escaping-special-characters/126272/3 "2008-01-17T02:19:45Z")

</div>

Woops… corrected code below:

> def escape\_string(str)  
> return Regexp.escape(str).gsub(/([:~!\<\>="])/,’\\\1’)  
> end
