首页 > 解决方案 > 正则表达式捕获组在 golang 的正则表达式构建器网站上未按预期运行

问题描述

本质上,我正在尝试在 golang 中建立捕获组。我正在使用以下网页,这似乎表明这应该像我写的那样正常工作

由于随机原因,这是时间敏感的,我相信你可以同情

    package main
import (
    "fmt"
    "regexp"
)

func main() {
    var r = regexp.MustCompile(`/number(?P<value>.*?)into|field(?P<field>.*?)of|type(?P<type>.*?)$/g`)
    fmt.Printf("%#v\n", r.FindStringSubmatch(`cannot unmarshal number 400.50 into Go struct field MyStruct.Numbers of type int64`))
    fmt.Printf("%#v\n", r.SubexpNames())
}

这当然会产生我没想到的结果,这与 regex builder 网站上的结果不一致。这可能是因为它是为使用不同的语言而构建的,但我不知道另一个更适合 golang 的网站也支持构建捕获组,并且可以在这个网站上使用帮助,因为它不符合我的习惯操舵室。

使用我提供的正则表达式格式的上述代码的输出是

[]string{"field", "", "", ""}
[]string{"", "value", "field", "type"}

我希望它尽可能接近

[]string{"field", "cannot unmarshal number (number)", "into go struct (Mystruct.Numbers)", "of type (int64)"}
[]string{"", "value", "field", "type"}

就像它在上面的正则表达式暂存器上显示的那样。

仅匹配匹配的第一个实例也很方便。

标签: regexgoslicecapture

解决方案


这看起来像一个XY 问题

直接从json.UnmarshalTypeError中提取数据,而不是解析错误的字符串表示。

这个程序:

var v MyStruct
err := json.Unmarshal([]byte(`{"numbers": 400.50}`), &v)
if e, ok := err.(*json.UnmarshalTypeError); ok {
    fmt.Printf("Value: %s\nStruct.Field: %s\nType: %s\n",
        e.Value, e.Struct+"."+e.Field, e.Type)
}

打印输出:

Value: number 400.50
Struct.Field: MyStruct.Numbers
Type: int64

在 Go 操场上运行它


推荐阅读