你如何捕获正则表达式的一部分到Ruby中的变量?

Gre*_*gle 1 ruby

我知道"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]
Run Code Online (Sandbox Code Playgroud)

但这似乎很草率.当然有一个正确的方法来做到这一点?

(我知道有人可能会写一个更简单的正则表达式来定位我想要的文本,让"string"[/regex/]方法工作,但这只是一个例子来说明问题,具体的正则表达式不是问题.)

Зел*_*ный 5

您可以将部分数量传递给[/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"
Run Code Online (Sandbox Code Playgroud)