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
+12k Golang : Determine if time variables have same calendar day
+16k Golang : ROT47 (Caesar cipher by 47 characters) example
+32.3k Golang : Convert []string to []byte examples
+20.6k Golang : Pipe output from one os.Exec(shell command) to another command
+8.3k Golang : How To Use Panic and Recover
+5.7k Unix/Linux : How to find out the hard disk size?
+6.6k Golang : Map within a map example
+8.4k Useful methods to access blocked websites
+18.8k Golang : Find IP address from string
+7.3k CloudFlare : Another way to get visitor's real IP address
+13.9k Golang : Convert spaces to tabs and back to spaces example
+17.5k Golang : Get future or past hours, minutes or seconds