6

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?

2 Answers 2

21

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this worked great, and is very similar to tokenizer.
How do we handle multiple separators ?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.