php - Go 相当于 PHP preg_match

标签 php regex go

我有一个通过我的 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/

相关文章:

javascript - jQuery slider PHP/HTML 问题

regex - Vim 用 unicode 字符替换

linux - Golang无法安装软件包

testing - 未调用的测试如何影响 Go 中的另一个测试?

python - 正则表达式检查它是否恰好是一个单词

go - 使用 Golang 与 hiveserver2 通信

php - 如何在 URL 中使用带有非英文符号的 file_get_contents()?

php - 如果我发布了包含数据库用户 pw 的 php 文件,我的 mysql 数据库是否容易受到攻击?

php - 在 PHP 中从 SQL 格式化时间戳的最简单方法是什么?

regex - 谷歌代码美化Delphi评论