Skip to content
instance method

String#=~

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

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.

See also #=== #[] #== #[]= also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0