2015-10-30 69 views
2

我有一套Elasticsearch的特殊字符,我需要使用Ruby转义。Ruby转义字符串中的一组特殊字符

它们是:+ - = && || > < ! () { } [ ]^" ~ * ? : \ /

我怎样才能得到任何字符串逃避这些字符?

感谢

+0

看看是否有帮助:http://stackoverflow.com/questions/4140582/ruby-escaping-special-characters-in-a-string –

回答

3

,因为它是陈述的问题还没有解决,因为“逃避随后的两个字符”是没有意义的。你期望得到什么结果“逃避”,比如&&

我相信,你想逃避一切单个字符,使&&成为\&\&|| - \|\|。这很容易。

to_escape = %w_+ - = & | > < ! () { } [ ]^" ~ * ? : \ /_ # C"mon, SO parser 
re = Regexp.union(to_escape) 
print 'str (f) | a || b'.gsub(re) { |m| "\\#{m}" } 
#⇒ str \(f\) \| a \|\| b 

另一种可能性是使用Regexp#escape,但它会逃跑多,可能比你需要(如空格)。

2

这是@ mudasobwa的答案的变化,使用的使用String#gsub形式用于更换散列:

escapees = %w$ + - = & | > < ! () { } [ ]^" ~ * ? : \/$ 
    #=> ["+", "-", "=", "&", "|", ">", "<", "!", "(", ")", "{", "}", 
    # "[", "]", "^", "\"", "~", "*", "?", ":", " /"] 
h = escapees.each_with_object({}) { |c,h| h[c] = "\\#{c}" } 
    #=> {"+"=>"\\+", "-"=>"\\-",..., " /"=>"\\ /"} 
h.default_proc = ->(h,k) { k } 

如果散列h没有一个关键kHash#default_proc=导致h[k]到返回k

s = 'str (f) | a || b' 
ss = s.gsub(/./,h) 
    #=> "str \\(f\\) \\| a \\|\\| b" 
puts ss 
    #=> str \(f\) \| a \|\| b