Ruby 正则表达式中 A z 和 ^ $ 的区别

问题描述:

在我阅读的文档中:

使用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 $ ...

如果你依赖正则表达式进行验证,你总是想使用 Az代码>.^$ 只会匹配到一个换行符,这意味着他们可以使用像 me@example.com <script>dangerous_stuff() 这样的电子邮件;</script> 并且仍然对其进行验证,因为正则表达式只能看到 之前的所有内容.

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 <script>dangerous_stuff();</script> and still have it validate, since the regex only sees everything before the .

我的建议是事先从用户名或电子邮件中完全删除新行,因为几乎没有正当理由.然后你可以安全地使用 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 ^ $.