I have two strings:
str1: "Connection to %s is down and error %d is thrown"
str2: "Connection to DataBase is down and error 401 is thrown"
In str2
, with the help of str1
, I want to find out what are the values in the place of %s
& %d
in str2
.
You can use fmt.Sscanf
, which is string and fromat version of 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)
}
playground: https://play.golang.org/p/5g5UcrHsunM
Note: It seems you are parsing an error. If the error is from Go, it is highly likely that it provides the data inside the error so you don't need to parse it mannually. And if you have control of the error, it is better to store the data inside.