Method: Regexp#=~

Defined in:
re.c

#=~(string) ⇒ Integer?

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:

/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:

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

Assigns nil if not matched:

/(?<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:

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:

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

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

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

Returns:



3694
3695
3696
3697
3698
3699
3700
3701
# File 're.c', line 3694

VALUE
rb_reg_match(VALUE re, VALUE str)
{
    long pos = reg_match_pos(re, &str, 0, NULL);
    if (pos < 0) return Qnil;
    pos = rb_str_sublen(str, pos);
    return LONG2FIX(pos);
}