Link to home
Start Free TrialLog in
Avatar of Member_2_6564143
Member_2_6564143

asked on

Regex required to extract multiple email addresses in string into groups

Hello Experts!


I require a regex that will  extract the following email addresses into separate groups, ie. Group 1, Group 2, Group 3. How can this be done for this string?


Test 1 <test1@gmail.com>Test 2 <test2@gmail.com>, Test 3 <test3@gmail.com>


Need something like this:


Group 1: test1@gmail.com

Group 2: test2@gmail.com

Group 3: test3@gmail.com


Thank you!



Avatar of Dr. Klahn
Dr. Klahn

Only three email addresses, always three email addresses, and formatted as shown?

^.*<(.*)>.*<(.*)>.*<(.*)>$
Avatar of Member_2_6564143

ASKER

Hi Dr. Khan,

The number of email addresses is dynamic.

Thanks

RN
My opinion about the logical extension of the above regex to multiple capture groups -- ^(.*<(.*).*>)*$ -- does not work when tested.

If the number of email addresses is indefinite, I would either

a) use a regex with more capture groups than could possibly occur, or
b) use strtok to tokenize the line, then use a regex with a single group and loop through the tokens

https://www.educative.io/edpresso/splitting-a-string-using-strtok-in-c

Of the two, (b) would be my choice as it is simple, clean and eliminates looking at an indefinite number of capture groups individually.

Side note:  If an email address ever appears in the list without enclosing angle brackets, none of the above approaches works correctly.
try this

Sub t701()
   
    Set reg = CreateObject("vbscript.regexp")

    For Each var In Array("j@j.com m@m.com  bob smith [bob.smith@mac.com] more@MORE.COM m@M.COM", "joe@joe.com", " sam@sam.com")
    Debug.Print "------" & var & "-----------"
 
        With reg
            .pattern = "[\w.%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b"
            .Global = True
            .MultiLine = True
            .IgnoreCase = True
            Set matches = .Execute(var)
        End With
        ans = ""
        For Each M In matches
            ans = ans & " " & M
        Next
        MsgBox ans
    Next
End Sub


ASKER CERTIFIED SOLUTION
Avatar of louisfr
louisfr

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