btald1331
btald1331

Reputation: 587

Go Language: A way to tokenize a string

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?

Upvotes: 5

Views: 14514

Answers (2)

Zombo
Zombo

Reputation: 1

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

Upvotes: 0

Rob Napier
Rob Napier

Reputation: 299265

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.

Upvotes: 21

Related Questions