Link to home
Start Free TrialLog in
Avatar of RobertNZana
RobertNZanaFlag for United States of America

asked on

Need code to remove invalid email addresses from string

I have a string that can contain from 1 to unlimited email addresses. They are separated by commas. So for example....

strEmails = "person1@email.com, person2@email.com, person3@email.com, person4@email.com"

I need to write a vb.net function that goes thru and ELIMINATES any invalid email addresses. So, for example...

strEmails = "person1@email.com, personINVALID1@, person2@email.com, person3@email.com, personINVALID2, person4@email.com"

The function would eliminate ALL invalid email addresses (personINVALID1@ and personINVALID2) and strEmails would now be equal to....

"person1@email.com, person2@email.com, person3@email.com, person4@email.com"

Can you please provide example code to do this? (Function input: a string; output: new string) Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Anurag Agarwal
Anurag Agarwal
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RobertNZana

ASKER

anurag_onnet - How can I return a regular (non-array) string as the result?
Use String.Join() as I demonstrate  : )

Of course, now that I tested it, it seems I had the arguments backwards!

Here is the appropriate code:
Public Function SanitizeEmailList(ByVal line As String) As String
    Dim candidates() As String = line.Split(",")
    Dim temp As New List(Of String)

    For Each candidate As String In candidates
        If Regex.IsMatch(candidate, "^[^@]+@[^@]+?\.[a-zA-Z]{2,6}$") Then
            temp.Add(candidate)
        End If
    Next

    Return String.Join(",", temp.ToArray())
End Function

Open in new window

Thanks. How can I return only those which FAIL the match reg ex?
Change line 6 to:

    If Not Regex.IsMatch(candidate, "^[^@]+@[^@]+?\.[a-zA-Z]{2,6}$") Then