instance method
String#=~
(::Regexp regex) -> ::Integer?
[T] (::String::_MatchAgainst[self, T] object) -> T
self =~ object → integer or nil
string.c
View on GitHub ↗
static VALUE
rb_str_match(VALUE x, VALUE y)
{
switch (OBJ_BUILTIN_TYPE(y)) {
case T_STRING:
rb_raise(rb_eTypeError, "type mismatch: String given");
case T_REGEXP:
return rb_reg_match(y, x);
default:
return rb_funcall(y, idEqTilde, 1, x);
}
}
When object is a Regexp, returns the index of the first substring in self matched by object, or nil if no match is found; updates Regexp-related global variables:
Example
'foo' =~ /f/ # => 0 $~ # => #<MatchData "f"> 'foo' =~ /o/ # => 1 $~ # => #<MatchData "o"> 'foo' =~ /x/ # => nil $~ # => nil
Note that string =~ regexp is different from regexp =~ string (see Regexp#=~):
Example
number = nil 'no. 9' =~ /(?<number>\d+)/ # => 4 number # => nil # Not assigned. /(?<number>\d+)/ =~ 'no. 9' # => 4 number # => "9" # Assigned.
If object is not a Regexp, returns the value returned by object =~ self.
Related: see Querying.