使用python正则表达式提取字段比较

2024-04-26 11:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

我知道我做错了。但我试了好几件事,都失败了。有人能帮我怎样用群组或其他更好的方法来取patter macthes吗。如果模式匹配,我想获取数字。这很顺利搜索但必须用重新编译在这种情况下。感谢你的帮助。在


Tags: keyinrebashforifmatchgroup
3条回答

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

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

>>> 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']

您正在捕获-:,而且还有多余的括号。以下是修改regex后的代码:

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()

印刷品:

^{pr2}$

看,所有的数字都被正确地提取出来了。在

相关问题 更多 >