From 3a637971a2a5939c7306ed7f9acd89689f37f25b Mon Sep 17 00:00:00 2001 From: naruse Date: Wed, 12 Dec 2018 06:10:29 +0000 Subject: Enchance MatchData docs [Bug #14450] From: Victor Shepelev git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@66350 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- re.c | 52 +++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 7 deletions(-) (limited to 're.c') diff --git a/re.c b/re.c index 1218877684..4b05a4b4c3 100644 --- a/re.c +++ b/re.c @@ -884,13 +884,51 @@ make_regexp(const char *s, long len, rb_encoding *enc, int flags, onig_errmsg_bu /* * Document-class: MatchData * - * MatchData is the type of the special variable $~, - * and is the type of the object returned by Regexp#match and - * Regexp.last_match. It encapsulates all the results of a pattern - * match, results normally accessed through the special variables - * $&, $', $`, $1, - * $2, and so on. - * + * MatchData encapsulates the result of matching a Regexp against + * string. It is returned by Regexp#match and + * String#match, and also stored in a global variable returned by + * Regexp.last_match + * + * Usage: + * + * url = 'https://docs.ruby-lang.org/en/2.5.0/MatchData.html' + * m = url.match(/(\d\.?)+/) # => # + * m.string # => "https://docs.ruby-lang.org/en/2.5.0/MatchData.html" + * m.regexp # => /(\d\.?)+/ + * # entire matched substring: + * m[0] # => "2.5.0" + * + * # Working with unnamed captures + * m = url.match(%r{([^/]+)/([^/]+)\.html$}) + * m.captures # => ["2.5.0", "MatchData"] + * m[1] # => "2.5.0" + * m.values_at(1, 2) # => ["2.5.0", "MatchData"] + * + * # Working with named captures + * m = url.match(%r{(?[^/]+)/(?[^/]+)\.html$}) + * m.captures # => ["2.5.0", "MatchData"] + * m.named_captures # => {"version"=>"2.5.0", "module"=>"MatchData"} + * m[:version] # => "2.5.0" + * m.values_at(:version, :module) + * # => ["2.5.0", "MatchData"] + * # Numerical indexes are working, too + * m[1] # => "2.5.0" + * m.values_at(1, 2) # => ["2.5.0", "MatchData"] + * + * == Global variables equivalence + * + * Parts of last MatchData (returned by Regexp.last_match) are also + * aliased as a global variables: + * + * * $~ is Regexp.last_match; + * * $& is Regexp.last_match[0]; + * * $1, $2 and so on are + * Regexp.last_match[i] (captures by number); + * * $` is Regexp.last_match.pre_match; + * * $` is Regexp.last_match.post_match; + * * $+ is Regexp.last_match[-1] (the last capture). + * + * See also "Special global variables" section in Regexp documentation. */ VALUE rb_cMatch; -- cgit v1.2.3