Posted about 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

!!("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

!!("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):

validates_format_of :content_type, with: /^image\/(jpeg|png)$/, message: 'must be a picture', multiline: true

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Author of this card:

Emanuel De
Last edit:
over 1 year 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