另一种方法而不是转义正则表达式模式? [英] Another way instead of escaping regex patterns?
问题描述
通常当我的正则表达式模式如下所示:
Usually when my regex patterns look like this:
http://www.microsoft.com/
然后我必须像这样逃脱它:
Then i have to escape it like this:
string.match(/http:\/\/www\.microsoft\.com\//)
有没有其他方法而不是像那样逃避它?
Is there another way instead of escaping it like that?
我希望能够像这样使用它http://www.microsoft.com,因为我不想转义所有模式中的所有特殊字符.
I want to be able to just use it like this http://www.microsoft.com, cause I don't want to escape all the special characters in all my patterns.
推荐答案
Regexp.new(Regexp.quote('http://www.microsoft.com/'))
Regexp.quote
只是转义任何具有特殊正则表达式含义的字符;它接受并返回一个字符串.注意 .
也是特殊的.引用后,您可以在传递给构造函数之前根据需要附加到正则表达式.一个简单的例子:
Regexp.quote
simply escapes any characters that have special regexp meaning; it takes and returns a string. Note that .
is also special. After quoting, you can append to the regexp as needed before passing to the constructor. A simple example:
Regexp.new(Regexp.quote('http://www.microsoft.com/') + '(.*)')
这会为路径的其余部分添加一个捕获组.
This adds a capturing group for the rest of the path.
这篇关于另一种方法而不是转义正则表达式模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!