Search code examples
crystal-lang

Extract substring with regex?


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.


Solution

  • 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