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
+15.2k Golang : Delete files by extension
+10.6k Golang : How to flush a channel before the end of program?
+4.4k Python : Create Whois client or function example
+21.1k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+8.8k Golang : interface - when and where to use examples
+16.1k Golang : How to tell if a file is compressed either gzip or zip ?
+34.3k Golang : Save image to PNG, JPEG or GIF format.
+26.4k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+6.7k Golang : Rename part of filename
+7.7k Android Studio : Import third-party library or package into Gradle Scripts
+7.4k Golang : Check if integer is power of four example
+10.8k How to tell if a binary(executable) file or web application is built with Golang?