Extract substring with regex?

484 Views Asked by At

String.match returns a MatchData, but how can I get the matched string from MatchData?

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

output:

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

Sorry I am new to crystal.

1

There are 1 best solutions below

1
On BEST ANSWER

You can access it via the well known group indexes, make sure to handle the nil (no match) case.

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

You can find more information about MatchData in its API docs