Tharanga Abeyseela
Tharanga Abeyseela

Reputation: 3483

Python regex matching

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

Upvotes: 0

Views: 124

Answers (1)

Tagc
Tagc

Reputation: 9072

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

Upvotes: 1

Related Questions