Regexp.escape的反义词是什么?

时间:2013-09-30 09:41:36

标签: ruby regex

Regexp.escape的反面是什么?

> Regexp.escape('A & B')
=> "A\\ &\\ B"
> # do something, to get the next result: (something like Regexp.unescape(A\\ &\\ B))
=> "A & B"

如何获得原始值?

4 个答案:

答案 0 :(得分:3)

replaces = Hash.new { |hash,key| key } # simple trick to return key if there is no value in hash
replaces['t'] = "\t"
replaces['n'] = "\n"
replaces['r'] = "\r"
replaces['f'] = "\f"
replaces['v'] = "\v"

rx = Regexp.escape('A & B')
str = rx.gsub(/\\(.)/){ replaces[$1] }

还要确保在{ib}输出#puts,因为#inspect默认会转义字符。

基本上,转义/引用会查找元字符,并预先添加\字符(必须在源代码中对字符串解释进行转义)。但是,如果我们从列表中找到任何控制字符:\t\n\r\f\v,则引用输出\字符跟随通过这个特殊字符翻译成ascii。

更新

我的解决方案遇到特殊字符问题(\ n,\ t等等),我在调查rb_reg_quote method的源代码后对其进行了更新。

更新2

replaces是哈希,它将转义字符(这就是为什么它在附加到gsub的块中使用)转换为非转义字符。它由没有转义字符的字符索引(序列中的第二个字符)并搜索未转义的值。唯一定义的值是控制字符,但还附加default_proc(附加到Hash.new的块),如果在散列中找不到值,则返回键。所以它的工作原理如下:

  1. 对于"n",它返回"\n",对于所有其他转义控制字符都是相同的,因为它是与关键字相关联的值
  2. 对于"(",它返回"(",因为没有与"("密钥相关联的值,哈希调用#default_proc,它自己返回密钥
  3. Regexp.escape转义的唯一字符是元字符和控制字符,因此我们不必担心字母数字。

    请查看http://ruby-doc.org/core-2.0.0/Hash.html#method-i-default_proc以获取有关#defoult_proc

    的文档

答案 1 :(得分:1)

使用\\(?=([\\\*\+\?\|\{\[\(\)\^\$\.\#\ ]))\

使用正则表达式替换

应该为你提供未转义的字符串,你只需要用那里的CrLf对应代替\r\n序列。

"There\ is\ a\ \?\ after\ the\ \(white\)\ car\.\ \r\n\ it\ should\ be\ http://car\.com\?\r\n"

未转义为:

"There is a ? after the (white) car. \r\n it should be http://car.com?\r\n"

并删除\ r \ n给出:

There is a ? after the (white) car. 
 it should be http://car.com?

答案 2 :(得分:1)

你可以使用这样的东西吗?

def unescape(s)
  eval %Q{"#{s}"}
end

puts unescape('A\\ &\\ B')

this question的信用。

codepad demo

如果您对正则表达式解决方案没问题,可以使用:

res = s.gsub(/\\(?!\\)|(\\)\\/, "\\1")

codepad demo

答案 3 :(得分:1)

试试这个

>> r = Regexp.escape("A & B (and * c [ e] + )")
# => "A\\ &\\ B\\ \\(and\\ \\*\\ c\\ \\[\\ e\\]\\ \\+\\ \\)"
>> r.gsub("\\(","(").gsub("\\)",")").gsub("\\[","[").gsub("\\]","]").gsub("\\{","{").gsub("\\}","}").gsub("\\.",".").gsub("\\?","?").gsub("\\+","+").gsub("\\*","*").gsub("\\ "," ")
# => "A & B (and * c [ e] + )"

基本上,这些(, ), [, ], {, }, ., ?, +, *是正则表达式中的元字符。还有\用作转义字符。

gsub()次调用链将转义后的模式替换为相应的实际值。

我确信有一种方法可以 DRY

更新 DRY版本,由user2503775建议

>> r.gsub("\\","")

<强>更新

以下是正则表达式中的特殊字符

    [,],{,},(,),|,-,*,.,\\,?,+,^,$,<space>,#,\t,\f,\v,\n,\r
相关问题