Python模式匹配正则表达式

Python模式匹配正则表达式,python,regex,pattern-matching,Python,Regex,Pattern Matching,我要分析该值: value=['0.203973Noerror(0)', '0.237207Noerror(0)','-1Timedout(-2)'] pattern=re.compile("\D\\(\d|[-]\d\\)") temp=[] for i in range(0,len(value)): err=pattern.match(value[i]) if err: temp=value[i] print(temp) 但当我处理代码时,结果是: [

我要分析该值:

value=['0.203973Noerror(0)', '0.237207Noerror(0)','-1Timedout(-2)']

pattern=re.compile("\D\\(\d|[-]\d\\)")

temp=[]

for i in range(0,len(value)):
    err=pattern.match(value[i])
    if err:
        temp=value[i]
print(temp)
但当我处理代码时,结果是:

[Noerror(0),Noerror(0),Timedout(-2)]
我不知道为什么会有这样的结果。。。请给我一些建议。

根据答案:


对于奖励积分,您可以将错误中的数字拆分为元组:

import re


results = []
pattern = re.compile(r'([a-z]+\([0-9-]+\))', flags=re.I)
value = ['0.203973Noerror(0)', '0.237207Noerror(0)','-1Timedout(-2)']

for v in value:
    match = pattern.search(v)
    if match:
        results.append(match.group(1))

print results
提供以下信息:

import re

value=['0.203973Noerror(0)', '0.237207Noerror(0)','-1Timedout(-2)']
temp=[]

for val in value:
    err = re.match(r'^([0-9.-]+)(.+)$', val)
    if err:
        temp.append(err.groups())

print temp
如果您只是想知道错误,那么:

[('0.203973', 'Noerror(0)'), ('0.237207', 'Noerror(0)'), ('-1', 'Timedout(-2)')]
给出:

temp2 = [ t[1] for t in temp ]
print temp2

match
更改为
search
,因为
match
总是从字符串开头开始匹配。您可以使用
re.search(r'[a-zA-Z]+\([0-9]+\)$,value[i])。group()
以下正则表达式也应该可以工作:
re.search(r'[^(0-9]+\([^)]+?\),value[i])。group()
。我还有一个问题,如果该值如下所示:value=['0.203973无错误(0)”,'0.237207无错误(0)”,-1超时(-2)”]我可以对代码应用相同的正则表达式规则吗?轻微修改-在组之间添加
\s*
re.match(r')^([0-9.-+)\s*(.+)$,val
给出:
[('0.203973','Noerror(0'),('0.237207','Noerror(0')),('-1','Timedout(-2)'))
temp2 = [ t[1] for t in temp ]
print temp2
['Noerror(0)', 'Noerror(0)', 'Timedout(-2)']