python - 清理嵌套的 re.sub 语句

标签 python regex database

有人可以帮我在 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/

相关文章:

mySQL 复合主键,部分键自增

MySQL - 连接在同一个表上?

python - Pandas 中两个数据框之间的差异

javascript - 在 python 中使用 json.loads() 的问题

JavaScript 匹配 RegExp 后的子串

php - 正则表达式获取括号内的文本

regex - 如何替换正则表达式匹配并在 Perl 中映射替换?

database - Spring Boot postgresql内嵌tomcat启动失败

Python MySQLdb不会释放表锁

python - xlsx get_worksheet_by_name 不返回任何内容?