我有一个小的PHP脚本,通过我的apache日志运行 - 我正在尝试将此脚本转换为Go.但是我在找到与PHP函数相当的好处时遇到了一些困难preg_match.
在我的PHP脚本中,我preg_match在日志文件的每一行上运行如下:
preg_match('/([.0-9]+) .*?\[([0-9a-zA-Z:\/+ ]+)\].*?"[A-Z]+ \/([^\/ ]+)\/([a-zA-Z0-9\-.]+).*" ([0-9]{3}) .*"(.*?)"$/', $line, $matches)
Run Code Online (Sandbox Code Playgroud)
在此日志上运行此表达式:
100.100.100.100 - - [23/Feb/2015:03:03:56 +0100]"GET /folder/file.mp3 HTTP/1.1"206 5637064" - ""AppleCoreMedia/1.0.0.12B466(iPhone; U; CPU) OS 8_1_3,如Mac OS X; da_dk)"
返回以下数组(我只对[1-6]感兴趣:
Array
(
[0] => 100.100.100.100 - - [23/Feb/2015:03:03:56 +0100] "GET /folder/file.mp3 HTTP/1.1" 206 5637064 "-" "AppleCoreMedia/1.0.0.12B466 (iPhone; U; CPU OS 8_1_3 like Mac OS X; da_dk)"
[1] => 100.100.100.100
[2] => 23/Feb/2015:03:03:56 +0100
[3] => folder
[4] => file.mp3
[5] => 206
[6] => AppleCoreMedia/1.0.0.12B466 (iPhone; U; CPU OS 8_1_3 like Mac OS X; da_dk)
)
Run Code Online (Sandbox Code Playgroud)
所以我的问题是 - 在Go中是否有相当的优势?我已经尝试了一些不同的正则表达式方法,但似乎找不到一个适合我的方法.
谢谢
首先你需要知道你可能需要修改正则表达式模式本身,因为go的正则表达式引擎与PHP的正则表达式引擎的行为不完全相同.两者都在使用PCRE正则表达式,其中PHP实现了比go更多的功能.但是,您的示例中的模式应该无需修改即可.
这里有一个示例程序,就像PHP一样preg_match():
package main
import "fmt"
import "regexp"
func main() {
str := `100.100.100.100 - - [23/Feb/2015:03:03:56 +0100] "GET /folder/file.mp3 HTTP/1.1" 206 5637064 "-" "AppleCoreMedia/1.0.0.12B466 (iPhone; U; CPU OS 8_1_3 like Mac OS X; da_dk)"`
r, _ := regexp.Compile(`([.0-9]+) .*?\[([0-9a-zA-Z:\/+ ]+)\].*?"[A-Z]+ \/([^\/ ]+)\/([a-zA-Z0-9\-.]+).*" ([0-9]{3}) .*"(.*?)"$`)
// Using FindStringSubmatch you are able to access the
// individual capturing groups
for index, match := range r.FindStringSubmatch(str) {
fmt.Printf("[%d] %s\n", index, match)
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
[0] 100.100.100.100 - - [23/Feb/2015:03:03:56 +0100] "GET /folder/file.mp3 HTTP/1.1" 206 5637064 "-" "AppleCoreMedia/1.0.0.12B466 (iPhone; U; CPU OS 8_1_3 like Mac OS X; da_dk)"
[1] 100.100.100.100
[2] 23/Feb/2015:03:03:56 +0100
[3] folder
[4] file.mp3
[5] 206
[6] AppleCoreMedia/1.0.0.12B466 (iPhone; U; CPU OS 8_1_3 like Mac OS X; da_dk)
Run Code Online (Sandbox Code Playgroud)
请查看关于go regex的手册:http://golang.org/pkg/regexp/