Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

String#match

match(pattern, offset = 0) → matchdata or nil
match(pattern, offset = 0) {|matchdata| ... } → object

Returns a MatchData object (or nil) based on self and the given pattern.

Note: also updates Special global variables at Regexp.

  • Computes regexp by converting pattern (if not already a Regexp).

    Example
    regexp = Regexp.new(pattern)
    
  • Computes matchdata, which will be either a MatchData object or nil (see Regexp#match):

    matchdata = <tt>regexp.match(self)

With no block given, returns the computed matchdata:

Example
'foo'.match('f') # => #<MatchData "f">
'foo'.match('o') # => #<MatchData "o">
'foo'.match('x') # => nil

If Integer argument offset is given, the search begins at index offset:

Example
'foo'.match('f', 1) # => nil
'foo'.match('o', 1) # => #<MatchData "o">

With a block given, calls the block with the computed matchdata and returns the block’s return value:

Example
'foo'.match(/o/) {|matchdata| matchdata } # => #<MatchData "o">
'foo'.match(/x/) {|matchdata| matchdata } # => nil
'foo'.match(/f/, 1) {|matchdata| matchdata } # => nil
See also #match? #lstrip! #lstrip #next also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0