Method: String#match

Defined in:
string.c

#match(pattern) ⇒ MatchData? #match(pattern, pos) ⇒ MatchData?

Converts pattern to a Regexp (if it isn’t already one), then invokes its match method on str. If the second parameter is present, it specifies the position in the string to begin the search.

'hello'.match('(.)\1')      #=> #<MatchData "ll" 1:"l">
'hello'.match('(.)\1')[0]   #=> "ll"
'hello'.match(/(.)\1/)[0]   #=> "ll"
'hello'.match('xx')         #=> nil

If a block is given, invoke the block with MatchData if match succeed, so that you can write

str.match(pat) {|m| ...}

instead of

if m = str.match(pat)
  ...
end

The return value is a value from block execution in this case.

Overloads:



3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
# File 'string.c', line 3341

static VALUE
rb_str_match_m(int argc, VALUE *argv, VALUE str)
{
    VALUE re, result;
    if (argc < 1)
  rb_check_arity(argc, 1, 2);
    re = argv[0];
    argv[0] = str;
    result = rb_funcall2(get_pat(re), rb_intern("match"), argc, argv);
    if (!NIL_P(result) && rb_block_given_p()) {
  return rb_yield(result);
    }
    return result;
}