问题
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?
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.
回答1:
Regexp.new(Regexp.quote('http://www.microsoft.com/'))
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.
回答2:
You can also use arbitrary delimiters in Ruby for regular expressions by using %r and defining a character before the regular expression, for example:
%r!http://www.microsoft.com/!
回答3:
Regexp.quote
or Regexp.escape
can be used to automatically escape things for you:
http://ruby-doc.org/core/classes/Regexp.html#M001195
The result can be passed to Regexp.new
to create a Regexp object, and then you can call the object's .match
method and pass it the string to match against (the opposite order from string.match(/regex/)
).
回答4:
You can simply use single quotes for escaping.
string.match('http://www.microsoft.com/')
you can also use %q{}
if you need single quotes in the text itself. If you need to have variables extrapolated inside the string, then use %Q{}
. That's equivalent to double quotes "
.
If the string contains regex expressions (eg: .*?()[]^$
) that you want extrapolated, use // or %r{}
回答5:
For convenience I just define
def regexcape(s)
Regexp.new(Regexp.escape(s))
end
来源:https://stackoverflow.com/questions/3518161/another-way-instead-of-escaping-regex-patterns