如何在正则表达式中转义所有具有特殊含义的字符 [英] How to escape all characters with special meaning in Regex

查看:39
本文介绍了如何在正则表达式中转义所有具有特殊含义的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是偶然发现了以下我无法理解的内容.当你像这样在 Ruby 中创建一个新的 Regexp 时:

I just stumbled upon the following which I can't quite get my head around. When you create a new Regexp in Ruby like so:

Regexp.new('http://www.example.com')

它将输出以下内容:

/http:\/\/www.example.com/

这是正确的,但没有转义 .;这意味着它基本上允许任何角色出现在那个地方.可以通过以下方式解决此问题:

which is correct, but doesn't escape the .; this means it basically allows for any character to be on that place. Getting around this can be achieved by doing:

Regexp.new(Regexp.escape('http://www.example.com'))
# => /http:\/\/www\.example\.com/

不过这个解决方案看起来有点奇怪,所以也许有更好的解决方案?

This solution looks a little odd though, so maybe there is a better one?

推荐答案

您可以:

Regexp.escape('http://www.example.com')

这将返回完全转义的字符串

That will return the fully escaped string

这篇关于如何在正则表达式中转义所有具有特殊含义的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆