never_had_a_name
never_had_a_name

Reputation: 93146

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?

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.

Upvotes: 31

Views: 21140

Answers (5)

Amber
Amber

Reputation: 526543

Regexp.quote or Regexp.escape can be used to automatically escape things for you:

https://ruby-doc.org/core/Regexp.html#method-c-escape

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

Upvotes: 8

Mike Blyth
Mike Blyth

Reputation: 4258

For convenience I just define

def regexcape(s)
  Regexp.new(Regexp.escape(s))
end

Upvotes: -1

Bernard
Bernard

Reputation: 17261

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

Upvotes: 0

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

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.

Upvotes: 71

user424705
user424705

Reputation:

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/!

Upvotes: 10

Related Questions