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
+4.5k Golang : Generate Interleaved 2 inch by 5 inch barcode
+28.7k Golang : How to get HTTP request header information?
+4.5k Javascript : How to loop over and parse JSON data?
+6.1k Golang : Transform lisp or spinal case to Pascal case example
+4.2k Golang : Constant and variable names in native language
+10.6k Golang : Get remaining text such as id or filename after last segment in URL path
+9.5k Golang : Underscore string example
+8k Golang : How to use Gorilla webtoolkit context package properly
+50.5k Golang : How to get struct field and value by name
+15.4k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+5.6k Nginx : Password protect a directory/folder
+61.5k Golang : Convert HTTP Response body to string