Go语言:将字符串进行分词的方法

huangapple go评论76阅读模式
英文:

Go Language: A way to tokenize a string

问题

我有一个Go程序,在其中我需要搜索多个字符串以找到特定的模式。这些字符串都是这样的:

 Destination: 149.164.31.169 (149.164.31.169) 

我想提取IP地址149.164.31.169,无论是中间的还是括号中的,它们始终相同。在Java中,我会使用字符串分词器来收集我需要的字符串部分,但是我在Go中没有找到类似的函数。

有人知道我如何实现这个吗?

英文:

I have a Go Program where I need to search through multiple strings for a specific pattern. The Strings all look like this:

 Destination: 149.164.31.169 (149.164.31.169) 

I'd like to just extract the IP 149.164.31.169, either the middle one or the one in parenthesis, they will always be the same. In Java I would do something along the lines of using a string tokenizer to gather the part of the string I need, but I didnn't find a function similar in go.

Does anyone know how I can achieve this?

答案1

得分: 20

你可以直接按空格分割字符串,并取中间的部分:

s := "Destination: 149.164.31.169 (149.164.31.169)"
parts := strings.Split(s, " ")
if len(parts) != 3 {
    panic("Should have had three parts")
}
println(parts[1])

还有很多其他的方法。strings 包是一个好去处。当然,如果你需要更复杂的处理,可以使用 regex 来进行正则表达式匹配,但在这里可能有点过头了。如果你真的需要一个分词器,可以看看 text/scanner,但对于这个问题来说,那太过复杂了。

英文:

You can just split on spaces and take the middle one:

s := "Destination: 149.164.31.169 (149.164.31.169)"
parts := strings.Split(s, " ")
if len(parts) != 3 {
	panic("Should have had three parts")
}
println(parts[1])

There are lots of other approaches. The strings package is the place to look. Of course if you need something much more complex, you can look at regex for regular expressions, but that'd be overkill here. If you really need a tokenizer, look at text/scanner, but again, that's way too much for this.

答案2

得分: 0

你也可以使用fmt.Sscanf来实现这个功能:

package main
import "fmt"

func extractIP(s string) string {
   var ip string
   fmt.Sscanf(s, "Destination: %v", &ip)
   return ip
}

func main() {
   ip := extractIP("Destination: 149.164.31.169 (149.164.31.169)")
   fmt.Println(ip == "149.164.31.169")
}

https://golang.org/pkg/fmt#Sscanf

英文:

You can also use fmt.Sscanf for this:

package main
import "fmt"

func extractIP(s string) string {
   var ip string
   fmt.Sscanf(s, "Destination: %v", &ip)
   return ip
}

func main() {
   ip := extractIP("Destination: 149.164.31.169 (149.164.31.169)")
   fmt.Println(ip == "149.164.31.169")
}

https://golang.org/pkg/fmt#Sscanf

huangapple
  • 本文由 发表于 2015年9月24日 08:45:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/32751653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定