go - 如何在 Go 中查找字符串的变量字段值?
问题描述
我有两个字符串:
str1: "与 %s 的连接已断开并抛出错误 %d"
str2:“与数据库的连接已关闭并引发错误401 ”
在str2
的帮助下str1
,我想找出%s
& %d
in的值是什么str2
。
解决方案
您可以使用fmt.Sscanf
,它是字符串和 fromat 版本fmt.Scan
:
package main
import (
"fmt"
)
func main() {
str1 := "Connection to %s is down and error %d is thrown"
str2 := "Connection to DataBase is down and error 401 is thrown"
var s string
var d int
_, err := fmt.Sscanf(str2, str1, &s, &d)
if err != nil {
panic(err)
}
fmt.Println(s, d)
}
操场: https: //play.golang.org/p/5g5UcrHsunM
注意:您似乎正在解析错误。如果错误来自 Go,很可能它提供了错误内部的数据,因此您无需手动解析它。如果您可以控制错误,最好将数据存储在里面。
推荐阅读
- python - 此功能不起作用,我不知道为什么
- datagrid - 在 Blazorise DataGrid 中克隆一行
- r - 在应用函数时有条件地合并两个 data.tables 的最有效方法
- javascript - Why is this HTML javascript wrapped in curly braces?
- docker - 打印容器 ID 的 Docker 映像
- numpy - Sympy lambdify 最大可操作性
- c - 以结构形式编写的矩阵的动态内存分配
- spring-boot - 释放 derby 文件锁
- c# - Blazor:命名空间“Microsoft.AspNetCore.Mvc.ApplicationParts”中不存在类型或命名空间名称“ApplicationPartAttributeAttribute”
- javascript - Nuxt FingerprintJS 模块服务器和客户端解决方案?