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
re.c
View on GitHub ↗
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);
}
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:
-
Is a regexp literal; see Regexp Literals.
-
Does not contain interpolations; see Regexp Interpolation.
-
Is at the left of the expression.
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