3.3. Escaping Special Characters

The class method Regexp.escape escapes any characters that are special characters used in regular expressions. Such characters include the asterisk, question mark, and brackets.

str1 = "[*?]"
str2 = Regexp.escape(str1)  # "\[\*\?\]"

The method Regexp.quote is an alias.

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.