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
+26.9k Golang : Force your program to run with root permissions
+9.4k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+6.1k PageSpeed : Clear or flush cache on web server
+14.3k Golang : Get uploaded file name or access uploaded files
+12.4k Golang : Encrypt and decrypt data with x509 crypto
+16.3k Golang : Loop each day of the current month example
+11.2k Golang : Calculate Relative Strength Index(RSI) example
+15.2k Golang : How to add color to string?
+12.3k Golang : How to display image file or expose CSS, JS files from localhost?
+25.3k Golang : Convert uint value to string type
+10.5k Swift : Convert (cast) String to Integer
+5.6k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday