我想用下面的模式提取字符串。Python正则表达式匹配
MsgTrace(65/26)noop:user=xxx=INBOX:cmd=534
正则表达式应该提取空操作
但是当我尝试follwong模式,它提取字符串“用户”为好。
ImapFetchComplete(56/39)user=xxxxxxxxxx
需要输出的字只包含以下模式。
)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
它看起来不像正则表达式有问题,请参阅https://regex101.com/r/ImzAyW/1。它不能匹配')somestring = xxxx'中的'somestring',因为没有':'。 –
它出了既somestring和somestring =,在这个例子中它输出noop和用户= xxxxxxxxxx –
我认为你的例子是不完整的(因为它的行为如预期,但只是偶然)。我认为你希望你的匹配模式是'r'\)([^:] *?):user =''这样你就不会捡起其余的线。我想你可能想要使用're.match()'而不是're.search()',如果你希望匹配在字符串的开始处开始。不过,如果您使用're.match()',则需要再调整一次正则表达式。 – jszakmeister