-1

I'm new to Python and am getting confused. I have a list of email strings and want to get the string after some specific text and before some text. So from the list below;

Email: promo@madeup.com
Email: dave@madeup.com
Email: john@madeup.com

get the following;

promo@madeup
dave@madeup
john@madeup

I've managed to get the first string (below) but can't seem to get all of them

import re

lines = '''
Email: promo@madeup.com
Email: dave@madeup.com
Email: john@madeup.com
'''


emailAddr = lines.split('Email:')[1] #start
emailAddr2 = emailAddr.split('.com')[0] #end
print(emailAddr2)
Barmar
  • 741,623
  • 53
  • 500
  • 612
Ken
  • 17
  • 3

2 Answers2

1

Use a lookbehind to match the Email: prefix before each email and the .com suffix.

emails = re.findall(r'(?<=Email: ).*(?=\.com)', lines)
print(emails)

Or just loop through the lines and remove the Email: prefix.

emails = [s.replace('Email: ', '').replace('.com') for s in lines.splitlines() if s]
print(emails)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Since parsing emails with regex is notoriously hard (https://stackoverflow.com/questions/201323/how-can-i-validate-an-email-address-using-a-regular-expression), I like your second example :-) – JonSG Feb 01 '23 at 17:54
  • Neither of my solutions does any real parsing. It assumes this is a fixed format file. It also only works for `.com` domains, it doesn't generalize. – Barmar Feb 01 '23 at 17:56
1
lines = '''
Email: promo@madeup.com
Email: dave@madeup.com
Email: john@madeup.com
'''

lines = lines.split('\n')
output = [x.split('Email:')[1].replace('.com','').strip() for x in lines if 'Email:' in x]
print(output)

will output:

['promo@madeup', 'dave@madeup', 'john@madeup']

if you want them all printed on a new line:

print('\n'.join(output))

will output:

promo@madeup
dave@madeup
john@madeup
Jacob Kearney
  • 391
  • 11
  • Thanks Jacob that works! I've change dit slightly to lines = lines.split('\n') output = [x.split('Email:')[1].split('.com')[0] for x in lines if 'Email:' in x] print(output) – Ken Feb 01 '23 at 18:00
  • hi Ken, good to hear, upvote answers you felt were useful and accept the best one :) – Jacob Kearney Feb 01 '23 at 18:02