Skip to content

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

class method

Regexp.new

Regexp.new(string, [options]) → regexp
Regexp.new(regexp) → regexp
Regexp.compile(string, [options]) → regexp
Regexp.compile(regexp) → regexp

Constructs a new regular expression from pattern, which can be either a String or a Regexp (in which case that regexp’s options are propagated), and new options may not be specified (a change as of Ruby 1.8).

If options is an Integer, it should be one or more of the constants Regexp::EXTENDED, Regexp::IGNORECASE, and Regexp::MULTILINE, or-ed together. Otherwise, if options is not nil or false, the regexp will be case insensitive.

Example
r1 = Regexp.new('^a-z+:\\s+\w+') #=> /^a-z+:\s+\w+/
r2 = Regexp.new('cat', true)     #=> /cat/i
r3 = Regexp.new(r2)              #=> /cat/i
r4 = Regexp.new('dog', Regexp::EXTENDED | Regexp::IGNORECASE) #=> /dog/ix
See also .last_match .quote .json_create .try_convert also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0