首页 > 解决方案 > 如何在 Python 中使用正则表达式提取名称列表?

问题描述

我刚开始学习正则表达式,下面显示了这个简单的文本:

text = """Mira is 15 years old, and her brother Danny is 12 years old. 
    Sarah and Jack, their parents, live in London."""

我想提取此字符串中的名称列表。我正在使用以下模式,但它不会给我正确的结果:

pattern = "[\w]* (?=is)"
result = re.findall(pattern, text)

而且我只得到了2 个名字,而应该是4 个名字!谁能帮助我知道我做错了什么?获得4个名字!谢谢

标签: pythonregex

解决方案


以下为您提供单词,以大写字母开头

>>> re.findall('([A-Z][a-z]+)', text)
['Mira', 'Danny', 'Sarah', 'Jack', 'London']

推荐阅读