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 = "https://rubyweekly.com/issues/537/"\
        .match(/(\w+).com\/.*\/(\d+)/)
=> #<MatchData "rubyweekly.com/issues/537/"
               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]:

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

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

     match = "https://rubyweekly.com/issues/537"\
             .match(/(?<issue>\d+)/)
     => #<MatchData "537" issue:"537">
    	
     match["issue"]
     => 537
    

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