【问题标题】:Ruby escaping a set of special characters in a stringRuby 转义字符串中的一组特殊字符
【发布时间】:2015-10-30 15:30:53
【问题描述】:

我有一组用于 Elasticsearch 的特殊字符,我需要使用 Ruby 进行转义。

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

如何获取任何字符串来转义这些字符?

谢谢

【问题讨论】:

标签: ruby elasticsearch


【解决方案1】:

问题没有解决方案,因为“转义两个后续字符”是没有意义的。你期望收到“转义”的结果,比如&&

我相信,您想转义所有单个字符,以便 && 变为 \&\&||\|\|。这很容易。

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
    

    【讨论】:

      猜你喜欢
      • 2011-05-07
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 2017-12-01
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      相关资源
      最近更新 更多