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
+5.7k Default cipher that OpenSSL used to encrypt a PEM file
+5.8k Golang : Levenshtein distance example
+18.7k Golang : Read directory content with os.Open
+7.8k Golang : Take screen shot of browser with JQuery example
+3.2k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+22.7k Golang : Find biggest/largest number in array
+22.3k Golang : Generate MD5 checksum of a file
+14.4k Golang : How to reverse elements order in map ?
+3.7k Facebook : How to place save to Facebook button on your website
+4.6k Golang : Grab news article text and use NLP to get each paragraph's sentences
+5.1k PageSpeed : Clear or flush cache on web server
+11.1k Golang : Search and extract certain XML data example