I'm working with the following regex (taken from the devise.rb
file that devise generates):
\A[^@\s]+@[^@\s]+\z
Usually, when I'm learning about a regex I use rubular. For example, if I wanted to learn about the regex /.a./
, I would set up my workspace as shown here:
Notice how I'm using multiple examples:
foo
bar
baz
And rubular is giving me feedback that both bar
and baz
match.
Now I'd like to learn about the regex that devise generates: /\A[^@\s]+@[^@\s]+\z/
. So I set up my rubular workspace as shown here here:
There isn't a match. It's because I have two examples:
foo@foo.com
cats@cat.com
But I was expecting them both to match. Why aren't both test strings matching?
This is because the regex /\A[^@\s]+@[^@\s]+\z/
is matching the start of the string with \A
and end of the string with \z
.
If you remove both \A
and \z
and instead try to match /[^@\s]+@[^@\s]+/
then it will match both email addresses as shown here:
Also, it's worth mentioning that the start and end of a string is different from the start and end of a line. Each are represented by four different patterns shown below and also on rubular in the Regex quick reference:
^ - Start of line
$ - End of line
\A - Start of string
\z - End of string
There can be multiple lines in a string; however, a single string goes from \A
to \z
. So to continue with this multiple email example. Replacing the start and end of a string patterns with the start and end of a line patterns to get: /^[^@\s]+@[^@\s]+$/
will also match, shown below and on rubular: