Posted over 3 years ago. Visible to the public. Repeats.

Ruby regular expression start/end line vs. start/end string

tl;dr: Most often you want to use \A and \z. Be careful when using ^ and $!

^ Start of line
$ End of line

Copy
!!("image/jpeg" =~ /^image\/(jpeg|png)$/) => true !!("image/png" =~ /^image\/(jpeg|png)$/) => true !!("application/javascript" =~ /^image\/(jpeg|png)$/) => false !!("application/javascript\nimage/jpeg\nfoo" =~ /^image\/(jpeg|png)$/) => true

\A Start of string
\z End of string

Copy
!!("image/jpeg" =~ /\Aimage\/(jpeg|png)\z/) => true !!("image/png" =~ /\Aimage\/(jpeg|png)\z/) => true !!("application/javascript" =~ /\Aimage\/(jpeg|png)\z/) => false !!("application/javascript\nimage/jpeg\nfoo" =~ /\Aimage\/(jpeg|png)\z/) => false

Rails warns you, when you try to use this:

The provided regular expression is using multiline anchors (^ or $), which may present a security risk. Did you mean to use \A and \z, or forgot to add the :multiline => true option? (ArgumentError)

You can remove this warning by changing your validation like this (Be sure you really want to):

Copy
validates_format_of :content_type, with: /^image\/(jpeg|png)$/, message: 'must be a picture', multiline: true
Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
Emanuel De
Last edit:
almost 2 years ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Emanuel De to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more