Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

Regexp.escape

Regexp.escape(string) → new_string

Returns a new string that escapes any characters that have special meaning in a regular expression:

Example
s = Regexp.escape('\*?{}.')      # => "\\\\\\*\\?\\{\\}\\."

For any string s, this call returns a MatchData object:

Example
r = Regexp.new(Regexp.escape(s)) # => /\\\\\\\*\\\?\\\{\\\}\\\./
r.match(s)                       # => #<MatchData "\\\\\\*\\?\\{\\}\\.">

Regexp.quote is an alias for Regexp.escape.

See also .compile .json_create .last_match also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0