Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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,我正在学习Python,并跟随sentdex的视频。我刚接触到正则表达式,并复制了他使用的代码。虽然年龄可以很好地打印出来,但当我尝试打印出姓名时,我只会得到“[]”作为输出 import re examplestring = ''' Jessica is 15 years old, and Daniel is 27 years old. Edward is 97, and his grandfather, Oscar, is 102 ''' ages = re.findall(r'\d

我正在学习Python,并跟随sentdex的视频。我刚接触到正则表达式,并复制了他使用的代码。虽然年龄可以很好地打印出来,但当我尝试打印出姓名时,我只会得到“[]”作为输出

import re
examplestring = ''' Jessica is 15 years old, and Daniel is 27 years    old.
Edward is 97, and his grandfather, Oscar, is 102
'''

ages = re.findall(r'\d{1,3}',examplestring)
name = re.findall(r'[A-Z], [a-z]*',examplestring)

print(ages)
print(name)

这里的问题是在编写表达式时使用逗号(,)

根据它的说法,它将寻找一个大写字母(a-Z),后跟逗号(,),然后是空格,后跟n个您的字符串不满足的字母

为了获得所需的结果,您需要消除逗号(,),并改用以下方法:

name = re.findall(r'[A-Z][a-z]*',examplestring)

有多个场景可以匹配名称。在你的情况下,如果名字是奥斯卡,那么你的正则表达式应该是这样的。
正则表达式:
[A-Z][A-Z]+
不应该有逗号,然后是空格,因为它将尝试查找CoryKramer提到的内容。
[A-Z]
表示第一个字母是单词,它是大写。
[a-z]
表示从第二个字母开始,所有字母都是小写的

我提到的是
+
,而不是
*
+
*
之间的区别是,
+
表示至少一次,因此如果您有word just O,则它将不匹配,您的数据应至少包含两个字符,如Os

*
表示零或更多的时间,所以如果您有单词just O,它将匹配,所以如果您的名字是字母表中的任何字母,它将匹配。因此,如果您认为您的名字只能是一个字母,请使用
*
,否则请使用
+

*示例:

+的示例:

是否希望
重新设置findall(r'[A-Z][A-Z]*',examplestring)
?那个逗号应该在做什么?我只会使用模式
r'[A-Z][A-Z]*'
,否则它会寻找例如
“O,scar”
@Navi,它对你有用吗?它应该是
+
,而不是
*
。我在回答中已经解释过了。