This was the tip of the week in the May 20, 2021 Ruby Weekly Newsletter.

Regular expression matches against strings return MatchData objects. In this week’s tip, we’ll look at three different methods to call on MatchData objects to get the data we’re looking for.

We’ll follow an example of matching against a URL using this:

match = ""\
=> #<MatchData ""
               1:"rubyweekly" 2:"537">
  1. MatchData#captures gives us an array of only the captures from the match. It’s the same as match.to_a[1..-1]:

     => ["rubyweekly", "537"]
  2. MatchData#pre_match and MatchData#post_match give us the parts of a String that appear before _and _after a match.

     => "https://"
     => "/"
  3. We can name captures by passing a ?<name> inside the capture group, like this:

     match = ""\
     => #<MatchData "537" issue:"537">
     => 537

Try these out the next time you’re using Regexp matching.