有人可以帮我在 python 中清理这个嵌套的正则表达式 (re.sub) 吗?我知道必须有更好的方法来做到这一点,但我不知道该怎么做。
re.sub('.*Chairman.*','Executive Director',re.sub('.*Managing Director.*','Executive Director',row['capacity']))
我有一列字符串 (row['capacity']) 作为集合的一部分从数据库中提取,我想遍历它,替换任何包含 'chairman' 或 'managing director 的行' 当我把它写到片场时,用'执行董事'。
这是完整的代码行:
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)
注意:'wrhk' 是一个列表元组。如有必要,我可以包含更多代码,但我真的只是希望有一种更简化的方法来处理我拥有的嵌套 re.sub
语句。
提前致谢!
最佳答案
您可以使用 |
将两个正则表达式与“或”连接起来:
re.sub(r'''(?x)
.*(
Chairman | Managing[]Director # or
).*
''','Executive Director', row['capacity'])
关于python - 清理嵌套的 re.sub 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8796627/