Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.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 = """ 9d 15h left <br /> some other text not important 12h 5m left <br />""" pattern = "((\d+)d)?.*left <br />" 但我要找的是 >>> re.finda

我有一个显示剩余时间的字符串:

text = """                9d 15h left <br />
                           some other text not important
                           12h 5m left <br />""" 
pattern = "((\d+)d)?.*left <br />"
但我要找的是

>>> re.findall(pattern,text)
[('9d', '9'),('', '')]

图案中缺少空格:

要么:

re.search(r"[ ]+((\d+)d)?.*left <br />", text).groups()
re.search(r“[]+(\d+)d)?*左
,text.groups()
或者在之前删除文本

re.search(r"((\d+)d)?.*left <br />", text.strip()).groups()
re.search(r“(\d+)d)?*left
,text.strip()).groups()
图案中缺少空格:

要么:

re.search(r"[ ]+((\d+)d)?.*left <br />", text).groups()
re.search(r“[]+(\d+)d)?*左
,text.groups()
或在前面删除文本

re.search(r"((\d+)d)?.*left <br />", text.strip()).groups()
re.search(r“(\d+)d)?*left
,text.strip()).groups()