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
+23.3k Golang : Read a file into an array or slice example
+18.9k Golang : Clearing slice
+10.3k Golang : Meaning of omitempty in struct's field tag
+6k Golang : Create new color from command line parameters
+29.7k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+19.1k Golang : Populate dropdown with html/template example
+7.4k Golang : Rename part of filename
+4.8k Python : Find out the variable type and determine the type with simple test
+9.1k Android Studio : Indicate progression with ProgressBar example
+5.5k Fix fatal error: evacuation not done in time problem
+9.9k Golang : Setting variable value with ldflags
+8.1k Golang : Qt splash screen with delay example