我有一个通过我的 apache 日志运行的小 PHP 脚本 - 我正在尝试将此脚本转换为 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)
在此日志上运行此表达式:
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-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)
)
所以我的问题是 - 在 Go 中是否有一个很好的等价物?我尝试了一些不同的正则表达式方法,但似乎找不到适合我的方法。
谢谢
最佳答案
首先您需要知道您可能需要修改正则表达式模式本身,因为 go 的正则表达式引擎的行为与 PHP 的正则表达式引擎并不完全相同。两者都使用 PCRE 正则表达式,其中 PHP 实现了比 go 更多的功能。但是,示例中的模式无需修改即可在 go 中运行。
这是一个 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)
}
}
输出:
[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)
请查看有关 go 正则表达式的手册:http://golang.org/pkg/regexp/
关于php - Go 相当于 PHP preg_match,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28715556/