2017-10-14 83 views
1

在Ruby文檔,它解釋:你如何解釋Ruby中發生了什麼? 'hello'.match('(。) 1' )[0]?

'hello'.match('(.)\1')[0] #=> "ll" 

它是如何(.)\1挑出 「LL」?我用包括雙字母在內的其他單詞替代了「你好」,比如「再見」和「奶酪」,我發現它會繼續挑選出雙字母。

然後我也擴展了更多的雙字母串,並添加括號更.S如:

puts 'boooooo'.match('(...)\1') #=> oooooo 

所以,我看得出來。對應於任何字符。但爲什麼它會返回翻倍的字母?

謝謝

+0

首先注意到如果[字符串#匹配](http://ruby-doc.org/core-2.4.0/String.html#method-i-match)的參數是字符串Ruby將其轉換爲正則表達式:'Regexp.new('(。)\ 1')#=> /(。)\ 1 /'。這通常會寫成''hello'[/(。)\ 1 /]#=>「ll',它使用方法[String#[\]](http://ruby-doc.org/core- 2.4.0/String.html#方法-I-5B-5D)。 –

回答

相關問題