2
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.

3
  • Change match to search, as match always starts matching from the beginning of the string. Commented Apr 21, 2017 at 7:29
  • You may use re.search(r'[a-zA-Z]+\(-?[0-9]+\)$', value[i]).group() Commented Apr 21, 2017 at 7:30
  • The following regular expression should work, too: re.search(r'[^(0-9]+\([^)]+?\)',value[i]).group(). Commented Apr 21, 2017 at 7:38

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

I have one more question, if the value is as below: value=['0.203973 No error (0)', '0.237207 No error (0)','-1 Timed out (-2)'] Can I apply to same regex rule on the code?
Slight amendment - add \s* between the groups: re.match(r'^([0-9.-]+)\s*(.+)$', val) gives: [('0.203973', 'Noerror (0)'), ('0.237207', 'Noerror (0)'), ('-1', 'Timedout (-2)')]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.