替换 与 \'在鲁比?
我正在尝试找出如何将 '
之类的引号替换为 \'
之类的内容。
我该怎么做?
我已经尝试过
"'".gsub("'","\\'")
,但它只给出一个空字符串。我在这里做错了什么?
I'm trying to figure out how to replace a quote like '
with something like \'
.
How would I do this?
I have tried
"'".gsub("'","\\'")
but it just gives an empty string. What am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这个怎么样
原因是
\'
在 gsub(正则表达式)中表示 匹配后,因此需要用\\' 和
\
显然被转义为\\
,最终为\\\\'
。示例
a
被替换为a
之后的所有内容。How about this
The reason is that
\'
means post-match in gsub (regex) and because of that it needs to be escaped with\\'
and\
is obviously escaped as\\
, ending up with\\\\'
.Example
a
is replaced with everything aftera
.$'
变量是匹配项右侧的字符串。在gsub
替换字符串中,相同的变量将是\'
——这就是问题所在。这应该有效:
The
$'
variable is the string to the right of the match. In thegsub
replacement string, the same variable would be\'
-- hence the problem.This should work:
这可能是一个错误......或者至少,它打破了我对最少惊喜原则的想法。
That might be a bug.. Or at the very least, something which breaks MY idea of the principle of least surprise.
我实际上使用过的两步方法......
只有在文本中明显不使用“¤”时才有效......
A two-step approach I've actually used...
Will only work if '¤' isn't used in the text obviously...
这样做怎么样:
不太漂亮,但我认为它有效......
How about doing this :
Not pretty but I think it works...