首页 > 解决方案 > 如何使用正则表达式循环过滤特定字符之前和之后的部分句子

问题描述

'我想提取“:”和“|”前后的文本 使用正则表达式并将其分成扬声器和标题。

'这样的句子很多,所以我需要写一个循环'

 text1='If I controlled the internet | Rives '
 text2='Life at 30,000 feet | Richard Brandson'
 text3='larry brilliant : A surprising idea for "solving" climate change'

标签: pythonregex

解决方案


如果您愿意使用纯字符串函数而不是正则表达式:

if '|' in text:
    title, speaker = text.split('|', 1)
elif ':' in text:
    speaker, title = text.split(':', 1)

推荐阅读