Sumanth
Sumanth

Reputation: 115

Pythonic way of finding regex match

I want to extract first name from email address. The email format is <first_name>@gmail.com. If email is not matched return None. I've written the following python code

def getFirstName(email):
    email_re = re.compile(r'(\w+)@gmail.com')
    match = email_re.search(email)
    if match == None:
        return None
    return match.group(1)

The None checking part looks ugly. Can someone suggest better pythonic way of doing it?

Upvotes: 2

Views: 147

Answers (2)

ryugie
ryugie

Reputation: 181

def get_first_name(email):
    match = re.search(r'(\w+)@gmail\.com', email)
    return match.group(1) if match else None
  • You need to escape the . in your pattern or else it'll match anything.
  • The with statement is not relevant here.

Upvotes: 0

Harald Nordgren
Harald Nordgren

Reputation: 12391

This is the Pythonic way of handling this. Well almost.

if match is None

Upvotes: 1

Related Questions