Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

String#match

(::Regexp | ::string pattern, ?::int offset) -> ::MatchData?
[T] (::Regexp | ::string pattern, ?::int offset) { (::MatchData matchdata) -> T } -> T?
match(pattern, offset = 0) → matchdata or nil
match(pattern, offset = 0) {|matchdata| ... } → object

Creates a MatchData object based on self and the given arguments; updates Regexp Global Variables.

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

    Example
    regexp = Regexp.new(pattern)
    
  • Calls regexp.match with self to compute matchdata. If offset is given, it is also passed (see Regexp#match).

With no block given, returns the computed matchdata or nil:

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

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

Example
'foo'.match(/o/) {|matchdata| matchdata } # => #<MatchData "o">

With a block given and nil matchdata, does not call the block:

Example
'foo'.match(/x/) {|matchdata| fail 'Cannot happen' } # => nil

Related: see Querying.

See also #match? #lstrip! #lstrip #next also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0