Ruby语言入门(18)- 内部类 -MatchData

上一篇 / 下一篇  2013-02-05 15:22:54 / 个人分类:语言

MatchData为处理与正则表达式的匹配过程相关的信息而设置的类. 可以通过下列途径得到该类的实例:
Regexp.last_match
Regexp#match, String#match
$~

实例方法

self[n]
返回第n个子字符串. 0表示整个匹配部分. 若n为负值,则从尾部算起(末尾的元素是第-1个). 若不存在第n个元素则返回nil.

/(this)(is)(a)(TEST)?/ =~ "thisisatest"
$~.to_a       
=> ["thisisa", "this", "is", "a", nil]
$~[0]         
=> "thisisa"
$~[4]         
=> nil        (不匹配)
$~[5]         
=> nil        (超出范围)
$~[-2]        
=> "a"

self[start..end]
返回从start位置开始到end位置结束的字符串集合.

$~[1..4]
=>["this", "is","a", nil]

self[start, length]
返回从start位置开始长度为length的字符串集合.
$~[1,4]
=>["this", "is","a", nil]

begin(n)
返回第n个子字符串的首字符的偏移量(offset). 0表示整个匹配部分. 若n超出范围则引发IndexError异常. 若第n个子字符串没有匹配部分则返回nil.

/(this)(is)(a)(TEST)?/ =~ "thisisatest"
$~.to_a       
=> ["thisisa", "this", "is", "a", nil]
$~.begin(0)
=>0 
$~.begin(1)
=>0
$~.begin(2)
=>4 
$~.begin(3)
=>6 
$~.begin(4)
=>nil 

end(n)
返回第n个子字符串的尾字符的偏移量(offset). 0表示整个匹配部分. 若n超出范围则引发IndexError异常. 若第n个子字符串没有匹配部分则返回nil.

/(this)(is)(a)(TEST)?/ =~ "thisisatest"
$~.to_a       
=> ["thisisa", "this", "is", "a", nil]
$~.end(0)
=>7 
$~.end(1)
=>4 
$~.end(2)
=>6 
$~.end(3)
=>7 
$~.end(4)
=>nil

captures 
返回一个包含$1,$2,...的数组. 与to_a不同的是,它不含$&. 若群组没有匹配部分,则相应的数组元素为nil.

/(this)(is)(a)(TEST)?/ =~ "thisisatest"
$~.to_a       
=> ["thisisa", "this", "is", "a", nil]
$&
=>"thisisa"
$~.captures
=>["this", "is", "a", nil]

length
size
返回子字符串的数量(与self.to_a.size相同).

$~.size
=>5

offset(n)
返回数组[start, end],它包含第n个子字符串的偏移量.

$~.offset(1)
=>[0,4]  ("this")

post_match
返回匹配部分之后的字符串(与$'相同).

$~.post_match
=>"test"

pre_match
返回匹配部分之前的字符串(与$`相同).

/(is)(test)?/ =~ "thisistest"
$~.pre_match
=>"this"

select { ... }
与self.to_a.select { ... } 相同.

string
返回匹配对象的拷贝.返回的字符串已被冻结.

$~.string
=>"thisisatest"

to_a
返回包含$&,$1,$2,... 的数组。

/(this)(is)(a)(TEST)?/ =~ "thisisatest"
$~.to_a       
=> ["thisisa", "this", "is", "a", nil]

to_s
返回整个匹配部分.

/(this)(is)(a)(TEST)?/ =~ "thisisatest"
$~.to_s 
=>"thisisa"


values_at(index1, index2, ...)
返回一个数组,它包括与正则表达式中第indexN个括号相匹配的子字符串. 与$&一样,第0个表示整个匹配部分.

/(this)(is)(a)(TEST)?/ =~ "thisisatest"
$~.values_at(1,2)
=>["this", "is"]




TAG:

 

评分:0

我来说两句

日历

« 2024-04-18  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 150427
  • 日志数: 185
  • 文件数: 6
  • 建立时间: 2007-08-06
  • 更新时间: 2015-01-06

RSS订阅

Open Toolbar