The Ruby %r{ } expression

%r{} is equivalent to the /.../ notation, but allows you to have “https://stackoverflow.com/” in your regexp without having to escape them:

%r{/home/user}

is equivalent to:

/\/home\/user/

This is only a syntax commodity, for legibility.

Edit:

Note that you can use almost any non-alphabetic character pair instead of ‘{}’.
These variants work just as well:

%r!/home/user!
%r'/home/user'
%r(/home/user)

Edit 2:

Note that the %r{}x variant ignores whitespace, making complex regexps more readable. Example from GitHub’s Ruby style guide:

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

Leave a Comment