Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中使用正则表达式提取名称列表?_Python_Regex - Fatal编程技术网

如何在Python中使用正则表达式提取名称列表?

如何在Python中使用正则表达式提取名称列表?,python,regex,Python,Regex,我刚开始学习正则表达式,下面是一个简单的文本: 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)&q

我刚开始学习正则表达式,下面是一个简单的文本:

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个名字!
谢谢

以下是单词,以大写字母开头

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

您正在检查后跟
is
的单词。但是
Sarah
Jack
后面没有
is
,因此它们不匹配。。。匹配名字的一般规则是什么?写一个正则表达式来查找大写单词是很容易的,但我认为不可能有一个正则表达式知道
Sarah
是一个名字,而
London
不是。问题是它应该给出4个名字,但这里有5个名字……当然,我明白。因此,如果我想使用这个答案,文本不应该包括伦敦,因为它以大写字母开头。@Ahmad hassan,你能告诉我为什么在单独的方括号中使用a-Z和a-Z吗?这意味着给我的答案是以大写字母开头的单词,大写字母后至少有一个小字符