Difference between \A \z and ^ $ in Ruby regular expressions

regex, ruby

Solution

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`.

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 `^` `$`.

Problem

In the documentation I read: Use \A and \z to match the start and end of the string, ^ and $ match the start/end of a line. 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 $ ...

Original source