regex - 正则表达式捕获组在 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"}
就像它在上面的正则表达式暂存器上显示的那样。
仅匹配匹配的第一个实例也很方便。
解决方案
这看起来像一个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
推荐阅读
- javascript - 设置属性 JavaScript
- google-kubernetes-engine - Knative 安装:无法拉取“gke.gcr.io/istio/proxy_init:1.2.10-gke.1”
- apache - 访问外部容器时 docker 容器的 403 错误服务器状态
- react-native - 如何在 react-native-calendars 包中设置滚动周历的日期
- ios - SceneKit 相机导致对象不显示
- android - Android:我如何创建一个 RecyclerView,我可以在其中自由拖放一个项目来做某些事情?
- d3.js - d3.js如何绘制带有垂直x轴标签的折线图
- javascript - 如何通过操作更改 Vuex 存储对象值?(vue.js)
- user-interface - 远程进入 Linux GUI
- spring-boot - Kotlin Multiplatform 中的 Spring Boot Gradle 依赖项