本文简要介绍ruby语言中 MatchData类 的用法。
MatchData 封装了将 Regexp 与字符串匹配的结果。它由 Regexp#match 和 String#match 返回,并存储在 Regexp.last_match 返回的全局变量中。
用法:
url = 'https://docs.ruby-lang.org/en/2.5.0/MatchData.html'
m = url.match(/(\d\.?)+/) # => #<MatchData "2.5.0" 1:"0">
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{(?<version>[^/]+)/(?<module>[^/]+)\.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"]
全局变量等价
最后 MatchData 的部分(由 Regexp.last_match 返回)也被别名为全局变量:
-
$~是Regexp.last_match; -
$&是Regexp.last_match[ 0 ]; -
$1、$2等是Regexp.last_match[ i ](按编号捕获); -
$`是Regexp.last_match.pre_match; -
$'是Regexp.last_match.post_match; -
$+是Regexp.last_match[ -1 ](最后一次捕获)。
另请参阅 Regexp 文档中的“Special global variables” 部分。
相关用法
- Ruby MatchData.pre_match用法及代码示例
- Ruby MatchData.mtch[i]用法及代码示例
- Ruby MatchData.named_captures用法及代码示例
- Ruby MatchData.length用法及代码示例
- Ruby MatchData.post_match用法及代码示例
- Ruby MatchData.captures用法及代码示例
- Ruby MatchData.offset用法及代码示例
- Ruby MatchData.string用法及代码示例
- Ruby MatchData.names用法及代码示例
- Ruby MatchData.end用法及代码示例
- Ruby MatchData.begin用法及代码示例
- Ruby MatchData.match_length用法及代码示例
- Ruby MatchData.inspect用法及代码示例
- Ruby MatchData.match用法及代码示例
- Ruby MatchData.values_at用法及代码示例
- Ruby MatchData.size用法及代码示例
- Ruby MatchData.regexp用法及代码示例
- Ruby MatchData.to_s用法及代码示例
- Ruby MatchData.to_a用法及代码示例
- Ruby Matrix lup()用法及代码示例
- Ruby Matrix unitary?()用法及代码示例
- Ruby Matrix symmetric?()用法及代码示例
- Ruby Matrix t()用法及代码示例
- Ruby Matrix identity()用法及代码示例
- Ruby Matrix hash()用法及代码示例
注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 MatchData类。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
