用正则表达式提取子字符串?

Extract substring with regex?

String.match returns a MatchData,但是如何从 MatchData 中获取匹配的字符串?

puts "foo bar".match(/(foo)/)

输出:

#<MatchData "foo" 1:"foo">

抱歉,我是 crystal 的新手。

您可以通过众所周知的组索引访问它,确保处理 nil(不匹配)情况。

match = "foo bar".match(/foo (ba(r))/)
if match
  # The full match
  match[0] #=> "foo bar"
  # The first capture group
  match[1] #=> "bar"
  # The second capture group
  match[2] #=> "r"
end

您可以在 API docs

中找到有关 MatchData 的更多信息