Golang : Find IP address from string
In this short tutorial, we will learn how to get the first occurrence of an IP address in a given string by searching for a matching pattern with regular expression.
package main
import (
"fmt"
"regexp"
)
func findIP(input string) string {
numBlock := "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])"
regexPattern := numBlock + "\\." + numBlock + "\\." + numBlock + "\\." + numBlock
regEx := regexp.MustCompile(regexPattern)
return regEx.FindString(input)
}
func main() {
var ip string
str := "this is a string that contain IP address 192.168.0.1 and you need to parse it"
ip = findIP(str)
fmt.Printf("The IP address in string is %q \n", ip)
}
Output :
go run parseipfromstring.go
The IP address in string is "192.168.0.1"
See also : Get client IP Address in Go
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.4k Golang : Return multiple values from function
+13.3k Golang : Convert(cast) int to float example
+11.1k Golang : calculate elapsed run time
+14.9k Golang : convert string or integer to big.Int type
+36k Golang : Read a text file and replace certain words
+13.6k Golang : Search folders for file recursively with wildcard support
+9.9k Golang : Read until certain character to break for loop
+9.5k Golang : Get UDP client IP address and differentiate clients by port number
+11.7k Python : Convert IPv6 address to decimal and back to IPv6
+5k Golang : How to verify input is rune?
+72.5k Golang : How to return HTTP status code?
+14.5k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy