Link to home
Start Free TrialLog in
Avatar of RobertNZana
RobertNZanaFlag 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?
Avatar of daveamour
Flag of United Kingdom of Great Britain and Northern Ireland image

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


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

Example: ",, INVALID_EMAIL@,"

The function should return "INVALID_EMAIL@".
Try this:

Dim strEmailAddresses As String = ",, INVALID_EMAIL@,"
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

Open in new window

For some reason this email address is passing when it should not:
Avatar of wdosanjos
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
But will work? This is valid.
Yes, that works.  I mean is a valid email, so Regex.IsMatch returns true.
Thanks. What is the reg ex statement to check if an email is valid?
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.