MichaelR
MichaelR

Reputation: 999

How to find string containing regex special chars with regex

I have the fallowing piece of code :

details =~ /.#{action.name}.*/

If action.name contains regular string such as "abcd" then everything goes ok , but if action.string contains special chars such as . or / ,im getting an exception.

Is there a way to check the action.name string without having to put \ before every special char inside action.name ?

Upvotes: 2

Views: 76

Answers (1)

Justin Ko
Justin Ko

Reputation: 46836

You can escape all special characters using Regexp::escape.

Try:

details =~ /.#{Regexp.escape(action.name)}.*/

Upvotes: 4

Related Questions