ruby regular expression begin method a bit confusing

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

m = /(.)(.)(\d+)(\d)/.match("THX1138.")  puts m[0]  c = m.captures #=> HX1138  puts c[0] #=> H puts  m.begin(0)   #=> 1  puts c[1] #=> X puts  m.begin(1)   #=> 1  puts c[2] #=> 113 puts  m.begin(2)   #=> 2 

I was expecting m.begin(1) to return 2 since X is two elements after the beginning of string.

I am reading the book well grounded rubyist which says

To get the information for capture n, you provide n as the argument to begin and/or end.

Similarly I was expecing m.begin(2) to rerturn 3.

回答1:

Read carefully:

Returns the offset of the start of the nth element of the match array in the string.

So the match array is actually [HX1138,H,X,113,8]

SO

   m.begin(0) => offset of HX1138 => 1 in "THX1138"    m.begin(1) => offset of H => 1      in "THX1138"    m.begin(2) => offset of X => 2      in "THX1138" 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!