提供的正则表达式使用多行锚点(^ 或 $) [英] The provided regular expression is using multiline anchors (^ or $)

查看:24
本文介绍了提供的正则表达式使用多行锚点(^ 或 $)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试编写图像验证格式,以确保 url 以 .png、.jpg 或 .gif 结尾.

I trying to write a Image validation format that makes sure url ends with either .png, .jpg or .gif .

class Product < ActiveRecord::Base

  mount_uploader :image_url

  validates :title, :presence => true,
            :uniqueness => true
  validates :image_url, :presence => true,
                        :format => {
                           :with => %r{.(gif|jpg|png)$}i,
                           :message => 'must be a URL for GIF, JPG or PNG image.'
                        }
end

但是当我启动我的服务器时.看到这个:

But when i start my server. seeing this:

提供的正则表达式使用了多行锚点(^ 或 $),可能存在安全风险.您是想使用 A 和 z,还是忘记添加 :multiline => true 选项?

推荐答案

^$ 都是线锚.如果用户要传入带有 http://www.foo.com/bar.png foo_bar_baz! 的字符串,那么您的正则表达式会说输入是有效的,因为它将匹配 .png 到换行符,这不是您想要的.

^ and $ are both line anchors. If a user were to pass in a string with http://www.foo.com/bar.png foo_bar_baz!, then your regex is going say that the input is valid because it will match .png to the newline, which is not what you want.

将上面的正则表达式改为 %r{.(gif|jpg|png)z}i.z 是字符串锚点的结尾,这是您想要的而不是行尾锚点.

Change your regex above to be %r{.(gif|jpg|png)z}i instead. The z is an end of string anchor, which is what you want instead of the end of line anchor.

关于另一个非常相似的问题有一些很好的答案:DifferenceRuby 正则表达式中的 A z 和 ^ $ 之间.

There are some great answers on another, very similar question: Difference between A z and ^ $ in Ruby regular expressions.

这篇关于提供的正则表达式使用多行锚点(^ 或 $)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆