Nithin Bekal

Posts About Notes Slides

Regular expression matching in Ruby with String#[]

04 Jun 2015

Today I learned a new way to check if a string matches a regular expression pattern in Ruby. Strings have a #[] method that lets us work with indexes, but we could also use them to check if a substring or a pattern exists.

s = "Hello, world!"

# Return sub-string if present
s['world'] #=> 'world'

# Returns nil if not present
s['bye'] #=> nil

# We can also use regular expressions there
s[/e..o/] #=> 'ello'

# Capture the last word in the string
s[/ ([a-zA-z]*)([^ ]*)$/, 1] #=> 'world'

So this allows us to do things like extracting parts of a string.

url = ''

protocol = url[/^(.*):\/\//, 1]               #=> 'http'
hostname = url[/^#{protocol}:\/\/(.*)\//, 1]  #=> ''

Because it returns nil when there is not match, we can also use it in conditions:

if url[URL_REGEX]
  'valid url'

This is yet another Ruby idiom that seems completely natural once you start using it. I’m surprised I haven’t come across this before.

Hi, I’m Nithin Bekal, a software craftsman with over 7 years of experience in shipping web applications. I mostly use Ruby, but lately have also been exploring Elixir. Co-founder of, and helping organize Rubyconf India. Tweet to me at @nithinbekal.