Regex for multiline email addresses?

I am looking for RegEx for several email addresses. For instance:

1) Single email address:

 johnsmith@email.com - ok 

2) Two line email address:

 johnsmith@email.com karensmith@emailcom - ok 

3) Two line email address:

 john smith@email.com - not ok karensmith@emailcom 

I tried the following:

 ((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*(\r\n)?)+)\r* 

But when I test it, it still matches the window if there is 1 valid email address, as in example 3.

I need a rule that lists all email addresses.

+4
source share
3 answers

What about:

 ^(((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*(\r\n)?\s?)+)*)$ 

Check the beginning of the line using "^" and the end - "$". Allow the optional space character with "\ s?".

Try http://myregexp.com/signedJar.html to test regex expressions.

+3
source

I would split the string into [\r\n]+ , and then check each address individually.

+1
source

I assume that you will probably need a multi-line parameter at the end of your regex (in most cases /m after regexp).

Change You can also add \A and \z anchors to mark the beginning and end of the input. Here is a good article on anchors.

Edit Quick and dirty Ruby example:

 /\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 the \A and \z bindings. The /m modifier is not required.

0
source

All Articles