Variable from regular expression

linkaiyi
Follow

get part of regular expression matched as variable

def get_email(staff_code, org_chart):
    if staff_code:
        result = org_chart.loc[org_chart['CommunityNickname'].apply(lambda x: re.match('BI_(\d+)_BI_CN', x).group(1) if re.match('BI_(\d+)_BI_CN', x) else '') == str(staff_code)]
        if len(result):
            email = result['Email'].iloc[0]
            if email:
                return email
    return None

or

>>> import re
>>> p = re.compile("lalala(I want this part)lalala")
>>> p.match("lalalaI want this partlalala").group(1)
'I want this part'

or

>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcom Reynolds")
>>> m.groupdict()
{'first_name': 'Malcom', 'last_name': 'Reynolds'}

import re
astr = 'lalalabeeplalala'
match = re.search('lalala(.*)lalala', astr)
whatIWant = match.group(1) if match else None
print(whatIWant)
Object has 0 attachments

Was this article helpful?

This article is viewed 10 times!

Recent Viewed Articles

0 Comments

Leave a Comment

Support