代码如下:

text = "Sir John Doe, married to Mrs Jane Doe, Sir Jack Doe, Mrs Mary Doe" 
splitter = re.split('Sir|Mrs', text)

我希望文本被单词"Sir"或"Mrs"分割,除非前面有字符串"married to".

Current output:

''
'John Doe, married to'
'Jane Doe,'
'Jack Doe,'
'Mary Doe'

Desired output:

''
'John Doe, married to Mrs Jane Doe,'
'Jack Doe,'
'Mary Doe'

推荐答案

我在这里使用re.findall方法:

text = "Sir John Doe, married to Mrs Jane Doe, Sir Jack Doe, Mrs Mary Doe"
matches = re.findall(r'\b(?:Sir|Mrs) \w+ \w+(?:, married to (?:Mrs|Sir) \w+ \w+)?', text)
print(matches)

此打印:

['Sir John Doe, married to Mrs Jane Doe', 'Sir Jack Doe', 'Mrs Mary Doe']

此处使用的正则表达式模式表示要匹配:

\b(?:Sir|Mrs)                         leading Sir/Mrs
  \w+ \w+                             first and last names
(?:
    , married to (?:Mrs|Sir) \w+ \w+  optional 'married to' followed by another name
)?                                    zero or one time

Python相关问答推荐

在上下文管理器中更改异常类型

在Python中为变量的缺失值创建虚拟值

Chatgpt API不断返回错误:404未能从API获取响应

滚动和,句号来自Pandas列

重新匹配{ }中包含的文本,其中文本可能包含{{var}

将输入管道传输到正在运行的Python脚本中

用合并列替换现有列并重命名

我如何使法国在 map 中完全透明的代码?

如何调整QscrollArea以正确显示内部正在变化的Qgridlayout?

在Python中,从给定范围内的数组中提取索引组列表的更有效方法

当点击tkinter菜单而不是菜单选项时,如何执行命令?

Python中的变量每次增加超过1

如何使用Numpy. stracards重新编写滚动和?

如何在Python请求中组合多个适配器?

将一个双框爆炸到另一个双框的范围内

Python pint将1/华氏度转换为1/摄氏度°°

Beautifulsoup:遍历一个列表,从a到z,并解析数据,以便将其存储在pdf中.

如何反转一个框架中列的值?

用来自另一个数据框的列特定标量划分Polars数据框中的每一列,

按条件计算将记录拆分成两条记录