Regex for multiline email addresses?
I'm looking for a RegEx
for multiple line email addresses.
For example:
1) Single email:
johnsmith@email.com - ok
2) Two line email:
johnsmith@email.com
karensmith@emailcom - ok
3) Two line email:
john smith@email.com 开发者_如何学Go- not ok
karensmith@emailcom
I've tried the following:
((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*(\r\n)?)+)\r*
But when I test it, it seems to still match ok if there is 1 valid email address as in example 3.
I need a rule which states all email addresses must be valid.
How about:
^(((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*(\r\n)?\s?)+)*)$
Check the beginning of the string using '^' and the end using '$'. Allow an optional whitespace character with '\s?'.
Try out http://myregexp.com/signedJar.html for testing regex expressions.
I'd split the string on [\r\n]+
and then test each address individualy.
My guess would be that you probably need a multiline option at the end of your regexp (in most cases /m
after the regexp).
Edit You might also want to add anchors \A
and \z
to mark the beginning and end of the input data. Here is a good article on anchors.
Edit Quick and dirty example working in Ruby:
/\A\w+@\w+\.\w+(\n\w+@\w+.\.\w+)*\z/
Will produce:
"test@here.pl\nthe@bar.pl".match(/\A\w+@\w+\.\w+(\n\w+@\w+\.\w+)*\z/)
=> #<MatchData "test@here.pl\nthe@bar.pl" 1:"\nthe@bar.pl">
"test@here.pl\nthebar.pl".match(/\A\w+@\w+\.\w+(\n\w+@\w+\.\w+)*\z/)
=> nil
"test@here.pl".match(/\A\w+@\w+\.\w+(\n\w+@\w+\.\w+)*\z/)
=> #<MatchData "test@here.pl" 1:nil>
"test@here".match(/\A\w+@\w+\.\w+(\n\w+@\w+\.\w+)*\z/)
=> nil
You can improve the regex and it should work. The key was to use \A
and \z
anchors. The /m
modifier is not required.
精彩评论