我想解析一个字符串xxxxx:yyyyy:zzz.aaa.bbb.cc:dd:ee:ff到Golang中的一个结构,我怎么能用多个分隔符':'和'.'来实现它.
编辑:
我想将字符串"xxxxx:yyyyy:zzz.aaa.bbb.cc:dd"拆分为以下结构类型
type Target struct {
Service string
Type string
Domain string
Plan string
Host string
Region string
Other string
}
Run Code Online (Sandbox Code Playgroud)
以便
Service = xxxxx
Type = yyyyy
Domain = zzzz
Plan = aaa
Host = bbb
Region = cc
Other = dd
Run Code Online (Sandbox Code Playgroud)
小智 26
你可以用
strings.FieldsFunc(input, Split)
Run Code Online (Sandbox Code Playgroud)
package main
import (
"fmt"
"strings"
)
func main() {
input := `xxxxx:yyyyy:zzz.aaa.bbb.cc:dd:ee:ff`
a := strings.FieldsFunc(input, Split)
t := Target{a[0], a[1], a[2], a[3], a[4], a[5], a[6]}
fmt.Println(t) // {xxxxx yyyyy zzz aaa bbb cc dd}
}
func Split(r rune) bool {
return r == ':' || r == '.'
}
type Target struct {
Service string
Type string
Domain string
Plan string
Host string
Region string
Other string
}
Run Code Online (Sandbox Code Playgroud)
输出:
{xxxxx yyyyy zzz aaa bbb cc dd}
Run Code Online (Sandbox Code Playgroud)
Naf*_*ail 10
您可以使用正则表达式来拆分字符串
import "regexp"
func splitWord(word string) []string {
array := regexp.MustCompile("[\\:\\,\\.\\s]+").Split(word, -1)
return array
}
Run Code Online (Sandbox Code Playgroud)
您可以使用此函数,它可以将字符串分割为多个符文:
import "fmt"
import "strings"
func SplitAny(s string, seps string) []string {
splitter := func(r rune) bool {
return strings.ContainsRune(seps, r)
}
return strings.FieldsFunc(s, splitter)
}
func main() {
words := SplitAny("xxxxx:yyyyy:zzz.aaa.bbb.cc:dd:ee:ff", ".:")
fmt.Println(strings.Join(words, " "))
}
Run Code Online (Sandbox Code Playgroud)
输出:
xxxxx yyyyy zzz aaa bbb cc dd ee ff
Run Code Online (Sandbox Code Playgroud)
或者甚至只用一行代码:
xxxxx yyyyy zzz aaa bbb cc dd ee ff
Run Code Online (Sandbox Code Playgroud)
eva*_*nal -1
好吧。这不是一个非常优雅的解决方案,但它至少应该让您开始并适用于您给出的特定示例。实际上,您可能希望添加一些错误处理或稍微概括逻辑以处理更广泛的输入集。
type Target struct {
Service string
Type string
Domain string
Plan string
Host string
Region string
Other string
}
func main() {
input := `xxxxx:yyyyy:zzz.aaa.bbb.cc:dd:ee:ff`
t := Target{}
tokens := strings.Split(input, ":")
t.Service = tokens[0]
t.Type = tokens[1]
subtokens := strings.Split(tokens[2], ".")
t.Domain = subtokens[0]
t.Plan = subtokens[1]
t.Host = subtokens[2]
t.Region = subtokens[3]
t.Other = tokens[3]
fmt.Printf("%v", t)
}
Run Code Online (Sandbox Code Playgroud)
工作示例在这里; https://play.golang.org/p/57ZyOfdbvo
| 归档时间: |
|
| 查看次数: |
9197 次 |
| 最近记录: |