的反义词是Regexp.escape什么?
> Regexp.escape('A & B')
=> "A\\ &\\ B"
> # do something, to get the next result: (something like Regexp.unescape(A\\ &\\ B))
=> "A & B"
我怎样才能得到原始值?
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] }
还要确保#puts在 irb 中输出,因为#inspect默认情况下会转义字符。
基本上转义/引用查找元字符,并预先\添加字符(必须对源代码中的字符串解释进行转义)。但是如果我们从 list: \t, \n, \r, \f,中找到任何控制字符\v,然后引用输出\字符后跟这个特殊字符转换为 ascii。
更新:
我的解决方案存在特殊字符(\n、\t 等)的问题,我在调查了rb_reg_quote 方法的源代码后对其进行了更新。
更新 2:
replaces是哈希,它将转义字符(这就是为什么它在附加到的块中使用gsub)转换为非转义字符。它按没有转义字符的字符(序列中的第二个字符)进行索引,并搜索未转义的值。唯一定义的值是控制字符,但也default_proc附加了(附加到的块Hash.new),如果在哈希中找不到值,则返回键。所以它是这样工作的:
"n"它返回"\n",所有其他转义控制字符都相同,因为它是与键关联的值"("它返回"(",因为没有与"("键关联的值,散列调用#default_proc返回键本身唯一被转义的字符Regexp.escape是元字符和控制字符,所以我们不必担心字母数字。
查看http://ruby-doc.org/core-2.0.0/Hash.html#method-i-default_proc以获取有关文档#defoult_proc
使用正则表达式替换使用\\(?=([\\\*\+\?\|\{\[\(\)\^\$\.\#\ ]))\
应该给你未转义的字符串,你只需\r\n要用 CrLf 对应物替换序列。
"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?
尝试这个
>> 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()将转义模式替换为相应的实际值。
我相信有办法把它弄干。
更新:user2503775 建议的 DRY 版本
>> r.gsub("\\","")
更新:
以下是正则表达式中的特殊字符
[,],{,},(,),|,-,*,.,\\,?,+,^,$,<space>,#,\t,\f,\v,\n,\r