Skip to content

Instantly share code, notes, and snippets.

@yannvery
Created January 26, 2016 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yannvery/938bd0186b2a4931c7ec to your computer and use it in GitHub Desktop.
Save yannvery/938bd0186b2a4931c7ec to your computer and use it in GitHub Desktop.
Regular expressions in Ruby

Regexp and match groups in ruby

There is multiple ways to use regular expressions with ruby.

Simple example

We're going to use the following pattern: /\A\d{3}-[\w-]+\.\w{3,4}\z/

pattern = /\A\d{3}-[\w-]+\.\w{3,4}\z/
pattern =~ "215-hello-world.avi"     # => 0
pattern =~ "test.mp3"                # => 0

Match Groups

A usefull feature is to group each matched string. For this we're going to use parentheses:

pattern = /\A(\d{3})-([\w-]+)\.(\w{3,4})\z/
pattern =~ "215-hello-world.avi"     # => 0
$1                                   # => "215"
$2                                   # => "hello-name"
$3                                   # => "avi"

MatchData object

If we use the match method we can look up match groups on the resulting MatchData object

pattern = /\A(\d{3})-([\w-]+)\.(\w{3,4})\z/
match_groups = pattern.match("215-hello-world.avi")
# => #<MatchData "215-hello-world...

match_groups[2]
# => "hello-world"

match_groups.captures
# => ["215", "hello-world", "avi"]

Named match groups

And what if we need to name our match groups?

pattern = /\A(?<num>\d{3})-(?<name>[\w-]+)\.(?<ext>\w{3,4})\z/
filename = "215-hello-world.avi"
match_groups = pattern.match(filename)
# => <MatchData "215-hello-world.avi" num:"215" name:"hello-world" ext:"avi">

match_groups[:ext]                        
# => "avi"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment