tags:

views:

57

answers:

4

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.

+5  A: 
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.

Matthew Flaschen
+1  A: 

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/)).

Amber
+1  A: 

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/!
Dean Pearce
While this helps for avoiding escaping `/` characters, it doesn't help for things like parentheses, brackets, and other special characters.
Amber
A: 

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{}

Alkaline