0

I want to extract the string with the following pattern.

MsgTrace(65/26)noop:user=xxx=INBOX:cmd=534

regex should extract noop

but when i try the follwong pattern , it extract the string "user" as well.

ImapFetchComplete(56/39)user=xxxxxxxxxx

need to output the word only contains the following pattern.

)somestring:  (it should extract the word somestring)

)somestring=xxxx (this shouldn't be extracted)
#!/usr/bin/python
import os
from subprocess import *
import os
import re

dir="/tmp/logs/"
os.chdir(dir)
for filename in os.listdir(dir):
    with open(filename) as fp:
        for line in fp:
             try:
                 print(re.search(r'\)([a-z]*?):',line).group(1))
             except:
                 pass
3
  • It does not look like there is a problem with the regex, see regex101.com/r/ImzAyW/1. It cannot match somestring in )somestring=xxxx because there is no :. Commented Jan 19, 2017 at 9:54
  • it out put both somestring and somestring= , in the example it output both noop and user=xxxxxxxxxx Commented Jan 19, 2017 at 10:02
  • I think your example is incomplete (because it's behaving as expected, though only by accident). I think you want your match pattern to be r'\)([^:]*?):user=' so that you don't end up picking up the rest of the line. And I think you probably want to be using re.match() instead of re.search() if you're expecting the match to start at the beginning of the string. You'll need to adjust the regex a little more if you use re.match() though. Commented Jan 19, 2017 at 10:09

1 Answer 1

1

Does this do what you want?

import re


def extract_from_string(s):
    match = re.search('(?<=\))\w*?(?=:)', s)
    return match.group(0) if match else None


if __name__ == '__main__':
    s1 = 'MsgTrace(65/26)noop:user=xxx=INBOX:cmd=534'
    s2 = 'ImapFetchComplete(56/39)user=xxxxxxxxxx'
    s3 = 'foo'
    print(extract_from_string(s1))  # 'noop'
    print(extract_from_string(s2))  #  None
    print(extract_from_string(s3))  #  None
Sign up to request clarification or add additional context in comments.

2 Comments

if you have both s1,s2 in the log, i need to extract only noop not user=xxxxx
@TharangaAbeyseela Gotcha, simple fix. Is this okay now?

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.