Read more

Ruby: Making your regular expressions more readable with /x and alternative delimiters

Henning Koch
April 03, 2012Software engineer at makandra GmbH

The following two hints are taken from Github's Ruby style guide Show archive.org snapshot :

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

If your regular expression mentions a lot of forward slashes, you can use the alternative delimiters %r(...), %r[...] or %r{...} instead of /.../.

 %r(/blog/2011/(.*))
 %r{/blog/2011/(.*)}
 %r[/blog/2011/(.*)]

If your regular expression is growing complex, you can use the /x modifier to ignore whitespace and comments or use named groups or Regexp.union Show archive.org snapshot :

regexp = %r{
  start         # some text
  \s            # white space char
  (group)       # first group
  (?:alt1|alt2) # some alternation
  end
}x

If you would like to match whitespace characters, you have to escape them if they are not contained in a character class.

Posted by Henning Koch to makandra dev (2012-04-03 11:40)