user5083592
user5083592

Reputation: 13

Python pattern matching regex

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)

I want parsing the value:

[Noerror(0),Noerror(0),Timedout(-2)]

But when I'm processing code, the result is:

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

I don't know why this result comes out... please advice to me.

Upvotes: 1

Views: 71

Answers (2)

Kind Stranger
Kind Stranger

Reputation: 1761

For bonus points, you can split the numbers from the errors into tuples:

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

Gives the following:

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

If you just want the errors, then:

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

Gives:

['Noerror(0)', 'Noerror(0)', 'Timedout(-2)']

Upvotes: 0

jpnkls
jpnkls

Reputation: 133

Based on DYZ answer:

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

Upvotes: 1

Related Questions