Dan
Dan

Reputation: 773

Python regex manipulation extract email id

First, I want to grab this kind of string from a text file

{kevin.knerr, sam.mcgettrick, mike.grahs}@google.com.au

And then convert it to separate strings such as

[email protected]

[email protected]

[email protected]

For example text file can be as:

Some gibberish words

{kevin.knerr, sam.mcgettrick, mike.grahs}@google.com.au

Some Gibberish words

Upvotes: 0

Views: 69

Answers (2)

rock321987
rock321987

Reputation: 11042

Python Code

ip = "{kevin.knerr, sam.mcgettrick, mike.grahs}@google.com.au"  
arr = re.match(r"\{([^\}]+)\}(\@\S+$)", ip)

#Using split for solution

for x in arr.group(1).split(","):
    print (x.strip() + arr.group(2))

#Regex Based solution

arr1 = re.findall(r"([^, ]+)", arr.group(1))
for x in arr1:
    print (x + arr.group(2))

IDEONE DEMO

Upvotes: 0

Jan
Jan

Reputation: 43199

As said in the comments, better grab the part in {} and use some programming logic afterwards. You can grab the different parts with:

\{(?P<individual>[^{}]+)\}@(?P<domain>\S+)
# looks for {
# captures everything not } into the group individual
# looks for @ afterwards
# saves everything not a whitespace into the group domain

See a demo on regex101.com.
In Python this would be:

import re
rx = r'\{(?P<individual>[^{}]+)\}@(?P<domain>\S+)'
string = 'gibberish {kevin.knerr, sam.mcgettrick, mike.grahs}@google.com.au gibberish'
for match in re.finditer(rx, string):
    print match.group('individual')
    print match.group('domain')

Upvotes: 1

Related Questions