RegExp - Matching email addresses that could be well mixed into other text

Hi All,

I have some VBA code that I am using to find email addresses in email bodies in Outlook (the full code can be found in another question linked here, but you probably only need to know what is posted in this question - I am referencing for completeness and context).

The code is now working as expected, but I need to work on the RegEx.

This is what I am using currently:

MyPattern = "\b\w*@\w*\.\w*\.\w*\b|\b\w*@\w*\.\w*\b"

It was pointed out in the other thread that this would match:

alan@example.com
alan@example.co.nz
alan_3285@example.com

but would also match:

@.
1@2.3.

and would not match:

alan.3285@example.com
alan_o'leary@example.com
alan-3285@example.com


So, I need to try and find an expression that will solve those cases too.

Thanks,

Alan.
LVL 23
AlanConsultantAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Terry WoodsIT GuruCommented:
If you'd like to go into great detail about what to try to match, there's a great article on the topic here: http://www.regular-expressions.info/email.html

The recommended email matching pattern from that article, which is intended to keep things simple, is:
\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b

Open in new window

(it's assumed an ignore-case option is turned on, so lower case  characters can also be matched)

That pattern would match all your examples, except for the one with the single quote. To allow that too, it would need to be adjusted to:
\b[A-Z0-9._%+'-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b

Open in new window


If you view the more complicated (and strictly more correct) patterns in the article, you'll understand why keeping things simple is desirable!
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AlanConsultantAuthor Commented:
Looks good to me!

Thank you,

Alan.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Regular Expressions

From novice to tech pro — start learning today.