Ruby 正则表达式中 A z 和 ^ $ 的区别 [英] Difference between A z and ^ $ in Ruby regular expressions

查看:21
本文介绍了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 ^ $.

这篇关于Ruby 正则表达式中 A z 和 ^ $ 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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