jaffa
jaffa

Reputation: 27350

Regex for multiline email addresses?

I'm looking for a RegEx for multiple line email addresses. For example:

1) Single email:

[email protected]  - ok

2) Two line email:

[email protected]
karensmith@emailcom  - ok

3) Two line email:

john  [email protected] - 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.

Upvotes: 6

Views: 1985

Answers (3)

Miki
Miki

Reputation: 7188

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:

"[email protected]\[email protected]".match(/\A\w+@\w+\.\w+(\n\w+@\w+\.\w+)*\z/)
=> #<MatchData "[email protected]\[email protected]" 1:"\[email protected]">
"[email protected]\nthebar.pl".match(/\A\w+@\w+\.\w+(\n\w+@\w+\.\w+)*\z/)
=> nil
"[email protected]".match(/\A\w+@\w+\.\w+(\n\w+@\w+\.\w+)*\z/)
=> #<MatchData "[email protected]" 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.

Upvotes: 0

Toto
Toto

Reputation: 91385

I'd split the string on [\r\n]+ and then test each address individualy.

Upvotes: 1

Mullins
Mullins

Reputation: 2364

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.

Upvotes: 4

Related Questions