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

The following two hints are taken from Github's Ruby style guide Archive :

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


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 Archive :

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

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

Henning Koch about 10 years ago
This website uses short-lived cookies to improve usability.
Accept or learn more