Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Another way instead of escaping regex patterns?

Tags:

regex

ruby

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.

like image 807
never_had_a_name Avatar asked Aug 19 '10 01:08

never_had_a_name


People also ask

Do I need to escape regex?

In order to use a literal ^ at the start or a literal $ at the end of a regex, the character must be escaped. Some flavors only use ^ and $ as metacharacters when they are at the start or end of the regex respectively. In those flavors, no additional escaping is necessary. It's usually just best to escape them anyway.

How do you escape expressions in regex?

The \ is known as the escape code, which restore the original literal meaning of the following character. Similarly, * , + , ? (occurrence indicators), ^ , $ (position anchors) have special meaning in regex. You need to use an escape code to match with these characters.

How do you escape special characters?

Escape CharactersUse the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped. Note: If you use braces to escape an individual character within a word, the character is escaped, but the word is broken into three tokens.

How do you escape a Metacharacter in regex?

To match any of the metacharacters literally, one needs to escape these characters using a backslash ( \ ) to suppress their special meaning. Similarly, ^ and $ are anchors that are also considered regex metacharacters.


1 Answers

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.

like image 124
Matthew Flaschen Avatar answered Oct 08 '22 20:10

Matthew Flaschen