【问题标题】:Regex for python requestpython请求的正则表达式
【发布时间】:2020-10-03 02:35:40
【问题描述】:

您好,我正在寻找一种解决方案来创建一个返回下一个结构的字典列表的函数

示例

example_dict = {"host":"146.204.224.152", 
               "user_name":"feest6811", 
               "time":"21/Jun/2019:15:45:24 -0700",
               "request":"POST /incentivize HTTP/1.1"}

数据如下:

146.204.224.152 - feest6811 [21/Jun/2019:15:45:24 -0700] "POST /incentivize HTTP/1.1" 302 4622
197.109.77.178 - kertzmann3129 [21/Jun/2019:15:45:25 -0700] "DELETE /virtual/solutions/target/web+services HTTP/2.0" 203 26554 
156.127.178.177 - okuneva5222 [21/Jun/2019:15:45:27 -0700] "DELETE /interactive/transparent/niches/revolutionize HTTP/1.1" 416 14701
*Keeps going more entries...*

我的函数如下所示:

import re
def logs():
    with open("assets/logdata.txt", "r") as file:
        logdata = file.read()
    pattern="""
(?P<host>.[\d.]*\s?)         #host
(?P<user_name>[\s\w-]*\s?)    #user_name
(?P<time>[\w\/\:\.\[\s-]*[\]\s])           #time
(?P<request>[\w\/\"\s.]*"?)     #request"""
    group=[]
    for item in re.finditer(pattern,logdata,re.VERBOSE):
        group.append(item.groupdict())
    return group    
    raise NotImplementedError()

然后返回类似这样的东西:

[{'host': '146.204.224.152 ',
  'user_name': '- feest6811 ',
  'time': '[21/Jun/2019:15:45:24 -0700]',
  'request': ' "POST /incentivize HTTP/1.1" 302 4622\n197.109.77.178 '},
 {'host': '- ',
  'user_name': 'kertzmann3129 ',
  'time': '[21/Jun/2019:15:45:25 -0700]',
  'request': ' "DELETE /virtual/solutions/target/web'},
 {'host': '+',
  'user_name': 'services',
  'time': ' ',
  'request': 'HTTP/2.0" 203 26554\n156.127.178.177 '}]

我可以改变什么来解决这个错误?

【问题讨论】:

    标签: python-3.x regex escaping


    【解决方案1】:

    试试这个:

        pattern="""
        (?P<host>\d{1,3}(?:\.\d{1,3}){3})\s-\s  #host (IPv4 only)
        (?P<user_name>[\s\w-]*?)\s?             #user_name
        \[(?P<time>[\w\/\:\.\s-]*)\]\s?         #time
        "(?P<request>.*?)"\s?                   #request
        (?P<code>\d{3})\s?                      #response code
        (?P<bytes>\d+)\s?                       #bytes sent or received
        """
    

    https://regex101.com/r/l7N52c/1

    【讨论】:

    • 非常感谢您的建议@Alexander Mashin。它如我所愿。
    • 这种模式给了我想要的结果,但是它在 user_name 的末尾添加了一个额外的空格,当我试图删除它时,它会与其他值混淆。在不更改其他值的情况下删除它的任何方法。 pattern=""" (?P[\d.]+)(?:\s*-\s*) (?P[\s\w-]*) [(?P
    【解决方案2】:

    您可以尝试以下正则表达式。

    (?P<host>[\d.]+)(?:\s*-\s*)(?P<user_name>\w+)(?:\s*\[)(?P<time>.*?)(?:\])(?:\s*)(?P<request>\".*?\")
    

    Demo

    【讨论】:

    • 这种模式给了我想要的结果,但是它在 user_name 的末尾添加了一个额外的空格,当我试图删除它时,它会与其他值混淆。 pattern=""" (?P[\d.]+)(?:\s*-\s*) (?P[\s\w-]*) [(?P
    • 简单。添加一个问号,使用户名不像编辑的回复那样贪婪。
    猜你喜欢
    • 2012-06-05
    • 2013-08-03
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多