Nithin Bekal Posts About Notes

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.

Nithin Bekal
Hi, I’m Nithin Bekal. I work at Shopify in Ottawa, Canada. Previously, co-founder of and WowMakers. Ruby is my preferred programming language, and the topic of most of my articles here, but I'm also a big fan of Elixir. Tweet to me at @nithinbekal.