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.3k Golang : alternative to os.Exit() function
+20.5k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+18.3k Golang : Count JSON objects and convert to slice/array
+5.8k Golang : How to fix html/template : "somefile" is undefined error?
+23.6k Golang : Get current file path of a file or executable
+15.4k CodeIgniter/PHP : Create directory if does not exist example
+11.2k Golang : How to check if a string starts or ends with certain characters or words?
+10.5k Golang : Change date format to yyyy-mm-dd
+5.1k Golang : Missing Subversion command
+7.6k Golang : Gaussian blur on image and camera video feed examples
+2k Golang : Fix go-cron set time not working issue
+16.7k Golang : Get command line arguments