Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaning up nested re.sub statements

Can someone help me clean up this nested regex (re.sub) in python, please? I know there must be a better way to do this but I can't figure how.

re.sub('.*Chairman.*','Executive Director',re.sub('.*Managing Director.*','Executive Director',row['capacity']))

I have a column of strings (row['capacity']) that I've pulled from a database as part of a set and I want to iterate through it, replacing any lines that contain 'chairman' or 'managing director' with 'Executive director' when I write it to the set.

here's the full line of code:

wrhkset = set (( row['organization'], row['lastname'], row['givenname'], re.sub('.*Chairman.*','Executive Director',re.sub('.*Managing Director.*','Executive Director',row['capacity'])) ) for row in wrhk)

NOTE: 'wrhk' is a tuple of lists. I can include more of the code if necessary, but I'm really just hoping for a more streamlined way to tackle the nested re.sub statements I have.

Thanks in advance!

like image 563
Nathan Avatar asked Feb 22 '26 13:02

Nathan


1 Answers

You could use a | to join two regexs with "or":

re.sub(r'''(?x)
     .*(
     Chairman | Managing[]Director     # or
     ).*     
     ''','Executive Director', row['capacity'])
like image 92
unutbu Avatar answered Feb 25 '26 03:02

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!