Python RegExp从匹配字符串中检索值

2024-06-17 13:13:03 发布

您现在位置:Python中文网/ 问答频道 /正文

全部成交

我在解析日志时遇到了一些不小的问题。你知道吗

我需要查看一个文件并检查行是否与模式匹配: 如果是,则获取此行中指定的ClientID。你知道吗

这条线看起来像:

17.02.09 10:42:31.242 TRACE [1245] GDS:     someText(SomeText).ClientID: '' -> '99071901'

所以我需要99071901。你知道吗

我试图构建regexp搜索模式,但它不完整..卡在“TRACE”上:

regex = '(^[(\d\.)]+) ([(\d\:)]+) ([\bTRACE\b]+) ([(\d)]+) ([\bGDS\b:)]+) ([\ClientID\b])'

脚本代码为:

log=open('t.log','r')
for i in log:
    key=re.search(regex,i)
    print(key.group()) #print string matching 
    for g in key:
        client_id=re.seach(????,g) # find ClientIt    
log.close()

如果你能给我一个如何解决这个挑战的提示,我将不胜感激。你知道吗

谢谢你。你知道吗


Tags: 文件keyinrelogfor模式trace
2条回答

您可以在感兴趣的模式中的这些部分周围使用捕获括号,然后使用group(n)访问这些部分,其中n是相应的组ID:

import re
s = "17.02.09 10:42:31.242 TRACE [1245] GDS:     someText(SomeText).ClientID: '' -> '99071901'"
regex = r"^([\d.]+)\s+([\d.:]+)\s+(TRACE)\s+\[(\d+)] GDS:.*?ClientID:\s*''\s*->\s*'(\d+)'$"
m = re.search(regex, s)
if m:
    print(m.group(1))
    print(m.group(2))
    print(m.group(3))
    print(m.group(4))
    print(m.group(5))

参见Python online demo

模式是

^([\d.]+)\s+([\d.:]+)\s+(TRACE)\s+\[(\d+)] GDS:.*?ClientID:\s*''\s*->\s*'(\d+)'$

its online demo here。你知道吗

请注意,您将字符类与组混淆:(...)组子模式并捕获它们,而[...]定义与单个字符匹配的字符类。你知道吗

你不需要太具体。您只需捕获部分并单独解析它们。你知道吗

让我们从一行开始,例如:

line = "17.02.09 10:42:31.242 TRACE [1245] GDS:     someText(SomeText).ClientID: '' -> '99071901'"

然后让我们添加第一个正则表达式来获取所有部分:

import re
line_regex = re.compile(r'(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+):\s+(.+)')
# now extract each section
date, time, level, thread, module, message = line_regex.match(line).groups()

现在,如果我们看一下不同的部分,它们将拥有我们需要的所有信息,以便做出更多的决定,或者进一步分析它们。现在让我们在显示正确类型的消息时获取客户机ID。你知道吗

client_id_regex = re.compile(r".*ClientID: '' -> '(\d+)'")

if 'ClientID' in message:
    client_id = client_id_regex.match(message).group(1)

现在我们有了client_id。你知道吗


只要把这个逻辑运用到你的循环中,你就万事大吉了。你知道吗

line_regex = re.compile(r'(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+):\s+(.+)')
client_id_regex = re.compile(r".*ClientID: '' -> '(\d+)'")

with open('t.log','r') as f:  # use with context manager to auto close the file
    for line in f:  # lets iterate over the lines
        sections = line_regex.match(line)  # make a match object for sections
        if not sections:
            continue  # probably you want to handle this case
        date, time, level, thread, module, message = sections.groups()
        if 'ClientID' in message:  # should we even look here for a client id?
            client_id = client_id_regex.match(message).group(1)
# now do what you wanted to do

相关问题 更多 >