python - 正则表达式不匹配

标签 python regex go

<分区>

我尝试使用正则表达式从日志文件中获取 SQL 信息

我需要的信息是SQL的运行时间,SQL语句,SQL的参数

这是我的代码:

package main

import (
    "os"
    "fmt"
    "io/ioutil"
    "regexp"
)

func main(){
    file,err:=os.OpenFile("./log.txt",os.O_RDWR,0755)
    if err !=nil{
        fmt.Println(err)
    }
    b,err:=ioutil.ReadAll(file)
    str:=string(b)
    r,err:=regexp.Compile(`\[ORM\][\w\W]+?(\d*.\d*ms|\d*.\d*s)\][ -]+\[([\w\W]+?)\]`)

    s:=r.FindAllStringSubmatch(str,-1)
    fmt.Println(s[0][3])
    fmt.Println(s[1][3])
}

这是我的日志样本

[ORM]2018/08/03 10:23:50 -[Queries/read] - [ OK / db.Query / 432.4ms] - [SELECT acc.*,gp.group_name,gp.group_id,org.org_name,group_concat(r.role_name) role_name FROM sys_account acc LEFT JOIN sys_org org on org.org_id=acc.org_id LEFT JOIN sys_group gp on gp.group_id=org.group_id LEFT JOIN sys_account_role ar on ar.acct_id=acc.acct_id and ar.is_del=0 LEFT JOIN sys_role r on r.role_id=ar.role_id where 1=1 and acc.acct_type=1 group by acc.acct_id order by acc.create_time desc LIMIT 0, 15] - `1` `ASDFASDF` nsq consumer2: INF 13 [RYOLST_Ch_admin/crm] (192.168.1.233:4150) received CLOSE_WAIT from nsqd nsq consumer2: INF 13 [RYOLST_Ch_admin/crm] (192.168.1.233:4150) beginning close nsq consumer2: INF 13 [RYOLST_Ch_admin/crm] (192.168.1.233:4150) readLoop exiting nsq consumer2: INF 13 [RYOLST_Ch_admin/crm] (192.168.1.233:4150) breaking out of writeLoop nsq consumer2: INF 13 [RYOLST_Ch_admin/crm] (192.168.1.233:4150) writeLoop exiting [ORM]2018/08/03 10:23:50 -[Queries/default] - [ OK / db.Query / 0.6ms] - [select * from sys_group where group_id=? ] - `111` `qwqwqw`

我希望如此打印出来

`1` `ASDFASDF`

`111``qwqwqw`

我现在只剩下最后一个我无法得到的参数

这些参数可能是多个也可能不是多个、你也可以在文件周围有太多的参数

我自己试过:

r,err:=regexp.Compile(`\[ORM\][\w\W]+?(\d*.\d*ms|\d*.\d*s)\][ -]+\[([\w\W]+?)\][ -]*((\W\w*\W{1,2})*)`)
r,err:=regexp.Compile(`\[ORM\][\w\W]+?(\d*.\d*ms|\d*.\d*s)\][ -]+\[([\w\W]+?)\][- ]*([^\n]*)`)

最佳答案

你可能想要这样的正则表达式:

var re = regexp.MustCompile(`\[ORM\][^-]* -\[[^]]*\] - \[ .* / .* / ([^]]*)] - \[([^]]*)\] - (.*)`)

https://play.golang.org/p/MUBzaiyyCWt

这假设数据格式正确,每行一个条目。如果不是,您可能无法使用正则表达式解析它,甚至这会对不包括字符串 [] 的查询做出一些假设(您可能会逃脱)。

首先,我会仔细检查您绝对不能首先以正确的格式获得此数据输出 - 如果可以,最好直接获得您想要的输出,甚至可能有一个单独的日志,甚至更好地将这样的指标发送到时间序列数据库以供以后分析。解析此类信息的日志并不是很好,尤其是在持续进行的情况下。

如果你必须解析日志,一些关于测试的建议:

  • 使用 play.golang.org 进行快速测试
  • 使用 regexp.MustCompile 检查您的正则表达式是否有效
  • 创建一个函数来解析这些行
  • 使用日志中的行编写一些测试来锻炼您的功能

关于python - 正则表达式不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51685744/

相关文章:

python - 同时使用 python3 和 python 2.7 时出现 numba 类型错误

python - 缩短 2 个变量的 IF 条件(相同比较)

python - django 管道抛出 ValueError : the file could not be found

python - Django:为 ModelForm 中的 ForeignKey 添加 "Add new"按钮

去库自动化

go - 如何在Win 10上本地测试Gol App Engine应用并使用app.yaml

python - 将时间段字符串转换为值/单位对

java - 匹配器不返回唯一结果

javascript - RegEx 删除所有样式但保留颜色和背景颜色(如果存在)

go - 无法卸载 BPF 程序