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
+6.6k Golang : Experimental emojis or emoticons icons programming language
+6.2k WARNING: UNPROTECTED PRIVATE KEY FILE! error message
+22k Golang : Match strings by wildcard patterns with filepath.Match() function
+20.1k Golang : Convert seconds to human readable time format example
+7.3k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+7.3k Golang : Check to see if *File is a file or directory
+10.9k Golang : Generate random elements without repetition or duplicate
+11.2k Golang : How to use if, eq and print properly in html template
+6.2k Golang & Javascript : How to save cropped image to file on server
+7.7k Golang : Example of how to detect which type of script a word belongs to
+6k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+4.4k Java : Generate multiplication table example