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
+14.7k Golang : Convert(cast) int to float example
+6.2k Golang : How to write backslash in string?
+19.8k Golang : Get current URL example
+6k Golang : Detect variable or constant type
+6.2k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+17.8k Golang : Read data from config file and assign to variables
+14.7k How to automatically restart your crashed Golang server
+11.6k Golang : Handle API query by curl with Gorilla Queries example
+26.2k Mac/Linux and Golang : Fix bind: address already in use error
+19.7k Golang : Close channel after ticker stopped example
+19.3k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?