user1617942
user1617942

Reputation: 233

Python - Regular Expression Assistance

I was wondering if I could get some assistance in coming up with a regular expression. I have a file that contains a long list of various aliases and the email address that alias forwards to. The file is in a format like this:

alias:[email protected]
alias2:[email protected]
alias3:[email protected]
alias4:[email protected]
alias5:[email protected]

How can I write a regular expression to just grab the part before the colon (alias, alias2, etc)? Sorry if this is a painfully easy question, I'm new to Python. Thanks in advance!

Upvotes: 0

Views: 317

Answers (2)

A. Rodas
A. Rodas

Reputation: 20689

I suggest you to use split() for this problem, since you have a very obvious delimiter. However, this is a solution with regular expressions:

lines = open(filename).readlines()
regex = re.compile("(.*):.*@gmail\.com")
aliases = [m.group(1) for m in map(lambda x: regex.match(x), lines) if m]

Upvotes: 1

matt
matt

Reputation: 1925

Here is a list-comprehension for it

first_parts = [
    line.split(':')[0]
    for line in file("addresses.txt").readlines()
    if ':' in line
]

It is similar to this

first_parts = []
lines = file("addresses.txt").readlines()
for lines in lines:
    if ":" in line:
        first = line.split(":")[0]
        first_parts.append(first)

Upvotes: 1

Related Questions