Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

Regexp.new

Regexp.new(string, options = 0, timeout: nil) → regexp
Regexp.new(regexp, timeout: nil) → regexp

With argument string given, returns a new regexp with the given string and options:

Example
r = Regexp.new('foo') # => /foo/
r.source              # => "foo"
r.options             # => 0

Optional argument options is one of the following:

  • A String of options:

    Example
    Regexp.new('foo', 'i')  # => /foo/i
    Regexp.new('foo', 'im') # => /foo/im
    
  • The bit-wise OR of one or more of the constants Regexp::EXTENDED, Regexp::IGNORECASE, Regexp::MULTILINE, and Regexp::NOENCODING:

    Example
    Regexp.new('foo', Regexp::IGNORECASE) # => /foo/i
    Regexp.new('foo', Regexp::EXTENDED)   # => /foo/x
    Regexp.new('foo', Regexp::MULTILINE)  # => /foo/m
    Regexp.new('foo', Regexp::NOENCODING)  # => /foo/n
    flags = Regexp::IGNORECASE | Regexp::EXTENDED |  Regexp::MULTILINE
    Regexp.new('foo', flags)              # => /foo/mix
    
  • nil or false, which is ignored.

  • Any other truthy value, in which case the regexp will be case-insensitive.

If optional keyword argument timeout is given, its float value overrides the timeout interval for the class, Regexp.timeout. If nil is passed as +timeout, it uses the timeout interval for the class, Regexp.timeout.

With argument regexp given, returns a new regexp. The source, options, timeout are the same as regexp. options and n_flag arguments are ineffective. The timeout can be overridden by timeout keyword.

Example
options = Regexp::MULTILINE
r = Regexp.new('foo', options, timeout: 1.1) # => /foo/m
r2 = Regexp.new(r)                           # => /foo/m
r2.timeout                                   # => 1.1
r3 = Regexp.new(r, timeout: 3.14)            # => /foo/m
r3.timeout                                   # => 3.14

Ruby version changes

  1. 3.2
See also .linear_time? .quote .last_match .timeout also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0