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 = 'http://nithinbekal.com/'

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

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

if url[URL_REGEX]
  'valid url'
else
  'invalid'
end

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. I work at Shopify in Ottawa, Canada. Previously, co-founder of CrowdStudio.in 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.