繁体   English   中英

python regex使用re.compile提取字段

[英]python regex extraction of fields using re.compile

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)

我知道我做错了。 但是我尝试了几件事,但失败了。 能有人帮我我怎么能获取使用组或任何更好的方式拍打macthes。 如果模式匹配,我想获取数字。 此作品所以用re.search顺利,但在这种情况下使用re.compile做到这一点。 感谢您的帮助。

您也可以将search与编译一起使用。 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']

您在捕捉-: ,也有多余的括号。 这是修改后的正则表达式的代码:

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

印刷品:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM