Skip to content

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

instance method

String#=~

(::Regexp regex) -> ::Integer?
[T] (::String::_MatchAgainst[self, T] object) -> T
string =~ regexp → integer or nil
string =~ object → integer or nil

Returns the Integer index of the first substring that matches the given regexp, or nil if no match found:

Example
'foo' =~ /f/ # => 0
'foo' =~ /o/ # => 1
'foo' =~ /x/ # => nil

Note: also updates Global Variables at Regexp.

If the given object is not a Regexp, returns the value returned by object =~ self.

Note that string =~ regexp is different from regexp =~ string (see Regexp#=~):

Example
number= nil
"no. 9" =~ /(?<number>\d+)/
number # => nil (not assigned)
/(?<number>\d+)/ =~ "no. 9"
number #=> "9"
See also #=== #[] #== #[]= also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0