I have strings in the following format name1 <[email protected]>. How can I use regex to pull only the name1 part out?
Also, how might I be able to do this if I had multiple such names and emails, say name1 <[email protected]>, name2 <[email protected]>?
3 Answers
Try using split:
In [164]: s = 'name1 <[email protected]>, name2 <[email protected]>'
In [166]: [i.split()[0] for i in s.split(',')]
Out[166]: ['name1', 'name2']
If you have just one name:
In [161]: s = 'name1 <[email protected]>'
In [163]: s.split()[0]
Out[163]: 'name1'
7 Comments
< would be much cleaner!<>. Its just a way of representing.str.split will behave the same if there are multiple spaces. 'name1 <someemail>'.split() returns the same output as 'name1 <someemail>'.split()str.split by default handles whitespaces.first, last <[email protected]> (which "real" emails frequently are) - the OP did not state this, but it'll be the case for any real-world collectionYou can start with (\w+)\s<.*?>(?:,\s)? (see on regex101.com), which relies on the fact that emails are surrounded by < >, and customize it as you see fit.
Note that this regex does not specifically look for emails, just for text surrounded by < >.
Don't fall down the rabbit hole of trying to specifically match emails.
import re
regex = re.compile(r'(\w+)\s<.*?>(?:,\s)?')
string = 'name1 <[email protected]>, name2 <[email protected]>'
print([match for match in regex.findall(string)])
outputs
['name1', 'name2']
1 Comment
import re
name = re.search(r'(?<! <)\w+', 'name1 <[email protected]>')
print(name.group(0))
>>> name1
Explanation:
(?<!...) is called a negative lookbehind assertion. I added ' <' into the ... as you are looking for the string that precedes the '<' of the email.
re.search(r'(?<!...), string_to_search)
https://docs.python.org/3/library/re.html
Edit/Forgot:
To search strings with multiple:
import re
regex = r"\w+([?<! <])"
multi_name = "name1 <[email protected]>, name2 <[email protected]>"
matches = re.finditer(regex, multi_name, re.MULTILINE)
for group, match in enumerate(matches, start=1):
print(f"Match: {match.group()}")
>>> name1
>>> name2
< >?