Avatar of RobertNZana
RobertNZana
Flag for United States of America asked on

Opposite of regex.matches?

Right now I'm using reg expressions to locate only valid email addresses within a long string. This string is a bunch of email addresses separated by a comma.

mc = Regex.Matches(strEmailAddresses, "([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})")
               
How can I find out only the ones that do NOT match? ie that FAIL the regular expression?
Visual Basic.NETASP.NET

Avatar of undefined
Last Comment
wdosanjos

8/22/2022 - Mon
daveamour

How is your string structured - ie how are email addresses split up within the string?
RobertNZana

ASKER
Simple string. All email addresses separated by comma. Purpose of this function is to report back those email addresses which are invalid.

Example: "myaddress1@mail.com, myaddress2@mail.com, INVALID_EMAIL@, myaddress3@mail.com"

The function should return "INVALID_EMAIL@".
wdosanjos

Try this:

Dim strEmailAddresses As String = "myaddress1@mail.com, myaddress2@mail.com, INVALID_EMAIL@, myaddress3@mail.com"
Dim emailAddr As String

For Each emailAddr in strEmailAddresses.Split(",")
	emailAddr = emailAddr.Trim()
	If Not Regex.IsMatch(emailAddr, "([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})") Then
		Console.WriteLine("'{0}' invalid email address", emailAddr)
	End If
Next

Open in new window

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
RobertNZana

ASKER
For some reason this email address is passing when it should not: myemail.@mail.net
ASKER CERTIFIED SOLUTION
wdosanjos

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
RobertNZana

ASKER
But will john.smith@att.net work? This is valid.
wdosanjos

Yes, that works.  I mean is a valid email, so Regex.IsMatch returns true.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
RobertNZana

ASKER
Thanks. What is the reg ex statement to check if an email is valid?
wdosanjos

Regex.IsMatch just returns true if the string provided matches the regular expression.  In this case the regular expression is to validate the email address format.