分享 #protip# Regex 尽量用 /A /z,而非 $ ^

fredwu · December 08, 2011 · Last by anklos replied at February 04, 2012 · 2625 hits

今天看到的——

https://gist.github.com/1444431

http://guides.rubyonrails.org/security.html#regular-expressions

用$ ^可能会有安全隐患。在 ruby 下推荐使用/A /z 来判断行的开始和结束。

额,还有这事情

其实也可可以/^your exgexp$/m 为啥是\A\z?WTF!好难看呀,我一直用\A\Z........

#2 楼 @hooopo 是不是因为 m flag 并不是所有情况下都能用的关系 我测试了一下似乎 "file.txt\n<script>alert('hello')</script>" =~ /^[\w\.\-\+]+$/m 是能通过的 "file.txt\n<script>alert('hello')</script>" =~ /\A[\w\.\-\+]+\z/m 则不行

m flag 好像是匹配多行,对于开头到/n 这段仍旧能匹配通过

记得 \A\Z 是字符串匹配 ^$ 是行匹配

看到这贴才注意到 rails guide 上的例子也是用这中 regx:

validates :legacy_code, :format => { :with => /\A[a-zA-Z]+\z/, :message => "Only letters allowed"}

You need to Sign in before reply, if you don't have an account, please Sign up first.