我需要帮助将正则表达式与 golang 集成。我想解析日志文件并创建一个在https://regex101.com/r/p4mbiS/1/上看起来很好的正则表达式
日志线如下所示:
57.157.87.86 - - [06/Feb/2020:00:11:04 +0100] "GET /?parammore=1&customer_id=1&version=1.56¶m=meaningful&customer_name=somewebsite.de&some_id=4&cachebuster=1580944263903 HTTP/1.1" 204 0 "https://www.somewebsite.com/more/andheresomemore/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0"
像这样的正则表达式:
(?P<ip>([^\s]+)).+?\[(?P<localtime>(.*?))\].+?GET\s\/\?(?P<request>.+?)\".+?\"(?P<ref>.+?)\".\"(?P<agent>.+?)\"
命名组的结果应如下所示:
ip: 57.157.87.86
请求:parammore=1&customer_id=1&...HTTP/1.1
参考:https ://www.somewebsite.com/more/andheresomemore/
代理:Mozilla/5.0(Windows NT 10.0;Win64;x64;rv:72.0)...
regex101.com 生成对我不起作用的 golang 代码。我试图改进它但没有成功。
golang 代码只返回整个字符串而不是组。
package main
import (
"regexp"
"fmt"
)
func main() {
var re = regexp.MustCompile(`(?P<ip>([^\s]+)).+?\[(?P<localtime>(.*?))\].+?GET\s\/\?(?P<request>.+?)\".+?\"(?P<ref>.+?)\".\"(?P<agent>.+?)\"`)
var str = `57.157.87.86 - - [06/Feb/2020:00:11:04 +0100] "GET /?parammore=1&customer_id=1&version=1.56¶m=meaningful&customer_name=somewebsite.de&some_id=4&cachebuster=1580944263903 HTTP/1.1" 204 0 "https://www.somewebsite.com/more/andheresomemore/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0"`
if len(re.FindStringIndex(str)) > 0 {
fmt.Println(re.FindString(str),"found at index",re.FindStringIndex(str)[0])
}
}
在这里找到小提琴https://play.golang.org/p/e0_8PM-Nv6i