Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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
使用re.compile提取字段的python正则表达式_Python_Regex - Fatal编程技术网

使用re.compile提取字段的python正则表达式

使用re.compile提取字段的python正则表达式,python,regex,Python,Regex,我知道我做错了。但我尝试了几件事,但都失败了。有人能帮我吗?我怎样才能用分组或其他更好的方法来取纸样。如果模式匹配,我想取数字。这在使用re.search时非常顺利,但在这种情况下必须使用re.compile。感谢您的帮助。您也可以将search与compile一起使用。(match仅在开头匹配)您正在捕获-和:,而且您还有多余的括号。下面是修改过的正则表达式的代码: array= ['gmond 10-22:13:29','bash 12-25:13:59'] regex = re.comp

我知道我做错了。但我尝试了几件事,但都失败了。有人能帮我吗?我怎样才能用分组或其他更好的方法来取纸样。如果模式匹配,我想取数字。这在使用re.search时非常顺利,但在这种情况下必须使用re.compile。感谢您的帮助。

您也可以将
search
与compile一起使用。(
match
仅在开头匹配)

您正在捕获
-
,而且您还有多余的括号。下面是修改过的正则表达式的代码:

array= ['gmond 10-22:13:29','bash 12-25:13:59']

regex = re.compile(r"((\d+)\-)?((\d+):)?(\d+):(\d+)$")

for key in array :
    res = regex.match(key)
    if res:
        print res.group(2)
        print res.group(5)
        print res.group(6)
印刷品:

import re

array = ["10-22:13:29", "12-25:13:59"]

regex = re.compile(r"^(\d+)\-?(\d+):?(\d+):?(\d+)$")
for key in array:
    res = regex.match(key)
    if res:
        print res.groups()

请参阅,所有数字都已正确提取。

如果您确定数组元素的格式,则可以使用
re.findall

('10', '22', '13', '29')
('12', '25', '13', '59')

究竟什么是
数组
它是一个
列表
(带
[]
)、一个
dict
(带键)还是一个
字符串
(要使用regexp解析)?你到底想做什么?@jadkik94:这是一个带字符串的列表
>>> import re
>>> array = ["10-22:13:29", "12-25:13:59"]
>>> regex = re.compile(r"\d+")
>>> for key in array:
...     res = regex.findall(key)
...     if res:
...         print res
...
['10', '22', '13', '29']
['12', '25', '13', '59']