instance method
Regexp#match
(::interned? str, ?::int offset) -> ::MatchData?
[T] (::interned? str, ?::int offset) { (::MatchData matchdata) -> T } -> T?
(nil, ?::int offset) ?{ (::MatchData matchdata) -> void } -> nil
match(string, offset = 0) → matchdata or nil
match(string, offset = 0) {|matchdata| ... } → object
re.c
View on GitHub ↗
static VALUE
rb_reg_match_m(int argc, VALUE *argv, VALUE re)
{
VALUE result = Qnil, str, initpos;
long pos;
if (rb_scan_args(argc, argv, "11", &str, &initpos) == 2) {
pos = NUM2LONG(initpos);
}
else {
pos = 0;
}
pos = reg_match_pos(re, &str, pos, &result);
if (pos < 0) {
rb_backref_set(Qnil);
return Qnil;
}
rb_match_busy(result);
if (!NIL_P(result) && rb_block_given_p()) {
return rb_yield(result);
}
return result;
}
With no block given, returns the MatchData object that describes the match, if any, or nil if none; the search begins at the given character offset in string:
Example
/abra/.match('abracadabra') # => #<MatchData "abra"> /abra/.match('abracadabra', 4) # => #<MatchData "abra"> /abra/.match('abracadabra', 8) # => nil /abra/.match('abracadabra', 800) # => nil string = "\u{5d0 5d1 5e8 5d0}cadabra" /abra/.match(string, 7) #=> #<MatchData "abra"> /abra/.match(string, 8) #=> nil /abra/.match(string.b, 8) #=> #<MatchData "abra">
With a block given, calls the block if and only if a match is found; returns the block’s value:
Example
/abra/.match('abracadabra') {|matchdata| p matchdata } # => #<MatchData "abra"> /abra/.match('abracadabra', 4) {|matchdata| p matchdata } # => #<MatchData "abra"> /abra/.match('abracadabra', 8) {|matchdata| p matchdata } # => nil /abra/.match('abracadabra', 8) {|marchdata| fail 'Cannot happen' } # => nil
Output (from the first two blocks above):
Example
#<MatchData "abra"> #<MatchData "abra"> /(.)(.)(.)/.match("abc")[2] # => "b" /(.)(.)/.match("abc", 1)[2] # => "c"