Ruby 正则表达式中 \A \z 和 ^ $ 之间的区别 [英] Difference between \A \z and ^ $ in Ruby regular expressions
问题描述
在我阅读的文档中:
使用\A和\z匹配字符串的开始和结束,^和$匹配一行的开始/结束.
Use \A and \z to match the start and end of the string, ^ and $ match the start/end of a line.
我将应用正则表达式来检查用户提交的用户名(或电子邮件地址是否相同).我应该将哪个表达式与模型中的 validates_format_of
一起使用?我无法理解其中的区别:我一直使用 ^ 和 $ ...
I am going to apply a regular expression to check username (or e-mail is the same) submitted by user. Which expression should I use with validates_format_of
in model? I can't understand the difference: I've always used ^ and $ ...
推荐答案
如果你依赖正则表达式进行验证,你总是想使用 \A
和 \z代码>.
^
和 $
只会匹配到一个换行符,这意味着他们可以使用像 me@example.com\n<script>dangerous_stuff() 这样的电子邮件;</script>
并且仍然对其进行验证,因为正则表达式只能看到 \n
之前的所有内容.
If you're depending on the regular expression for validation, you always want to use \A
and \z
. ^
and $
will only match up until a newline character, which means they could use an email like me@example.com\n<script>dangerous_stuff();</script>
and still have it validate, since the regex only sees everything before the \n
.
我的建议是事先从用户名或电子邮件中完全删除新行,因为几乎没有正当理由.然后你可以安全地使用 \A
\z
或 ^
$
.
My recommendation would just be completely stripping new lines from a username or email beforehand, since there's pretty much no legitimate reason for one. Then you can safely use EITHER \A
\z
or ^
$
.
这篇关于Ruby 正则表达式中 \A \z 和 ^ $ 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!