Skip to content

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

instance method

Regexp#=~

regexp =~ string → integer or nil

Returns the integer index (in characters) of the first match for self and string, or nil if none; also sets the rdoc-ref:Regexp Global Variables:

Example
/at/ =~ 'input data' # => 7
$~                   # => #<MatchData "at">
/ax/ =~ 'input data' # => nil
$~                   # => nil

Assigns named captures to local variables of the same names if and only if self:

Example:

Example
/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ '  x = y  '
p lhs # => "x"
p rhs # => "y"

Assigns nil if not matched:

Example
/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ '  x = '
p lhs # => nil
p rhs # => nil

Does not make local variable assignments if self is not a regexp literal:

Example
r = /(?<foo>\w+)\s*=\s*(?<foo>\w+)/
r =~ '  x = y  '
p foo # Undefined local variable
p bar # Undefined local variable

The assignment does not occur if the regexp is not at the left:

Example
'  x = y  ' =~ /(?<foo>\w+)\s*=\s*(?<foo>\w+)/
p foo, foo # Undefined local variables

A regexp interpolation, #{}, also disables the assignment:

Example
r = /(?<foo>\w+)/
/(?<foo>\w+)\s*=\s*#{r}/ =~ 'x = y'
p foo # Undefined local variable
See also #=== #~ #== #as_json also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0