MatchData

=~ ‘运算符’不是找到匹配的唯一方式。Regexp 类也有 match 方法。这与 =~ 类似,但是,当匹配时,它返回 MatchData 对象而不是整数。MatchData 对象包含模式匹配的结果。乍一看,这似乎是一个字符串…

match.rb
  1. puts( /cde/ =~ 'abcdefg' ) #=> 2
  2. puts( /cde/.match('abcdefg') ) #=> cde

实际上,它是 MatchData 类的一个实例,它包含一个字符串:

  1. p( /cde/.match('abcdefg') ) #=> #<MatchData:0x28cedc8>

MatchData 对象可以包含组或“捕获”(captures),这些可以使用 to_acapture 方法在数组中返回,如下所示:

matchdata.rb
  1. x = /(^.*)(#)(.*)/.match( 'def myMethod # This is a very nice method' )
  2. x.captures.each{ |item| puts( item ) }

以上显示:

  1. def myMethod
  2. #
  3. This is a very nice method

请注意,capturesto_a 方法之间存在细微差别。第一个只返回捕获值:

  1. x.captures #=>["def myMethod ","#"," This is a very nice method"]

第二个返回原始字符串(在索引 0 处),然后是捕获值:

  1. x.to_a #=>["def myMethod # This is a very nice method","def myMethod ","#"," This is a very nice method"]