我知道"string"[/regex/]
,它返回匹配的字符串部分。但是,如果我只想返回字符串的捕获部分,该怎么办?
我有绳子"1952-FEB-21_70_The_Case_of_the_Gold_Ring.mp3"
。我想title
将文本存储在变量中The_Case_of_the_Gold_Ring
。
我可以用正则表达式捕获这部分/\d_(?!.*\d_)(.*).mp3$/i
。但是写Ruby"1952-FEB-21_70_The_Case_of_the_Gold_Ring.mp3"[/\d_(?!.*\d_)(.*).mp3$/i]
返回0_The_Case_of_the_Gold_Ring.mp3
的不是我想要的。
我可以通过写得到我想要的
"1952-FEB-21_70_The_Case_of_the_Gold_Ring.mp3" =~ /\d_(?!.*\d_)(.*).mp3$/i
title = $~.captures[0]
但这似乎草率。当然有适当的方法可以做到这一点吗?
(我知道有人可能可以编写一个更简单的正则表达式来定位我想要的文本,从而使该"string"[/regex/]
方法起作用,但这只是说明问题的一个示例,特定的正则表达式不是问题。)
您可以将零件编号传递给[/regexp/, index]
方法:
=> string = "1952-FEB-21_70_The_Case_of_the_Gold_Ring.mp3"
=> string[/\d_(?!.*\d_)(.*).mp3$/i, 1]
=> "The_Case_of_the_Gold_Ring"
=> string[/\d_(?!.*\d_)(.*).mp3$/i, 0]
=> "0_The_Case_of_the_Gold_Ring.mp3"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句