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
+13.8k Golang : Check if an integer is negative or positive
+13.6k Golang : Strings comparison
+14.4k Golang : How to convert a number to words
+3.8k Golang : Switch Redis database redis.NewClient
+22.8k Golang : Set and Get HTTP request headers example
+7.2k Golang : Gorrila mux.Vars() function example
+7.6k Golang : Detect sample rate, channels or latency with PortAudio
+24.5k Golang : Change file read or write permission example
+4.7k Linux : sudo yum updates not working
+6.9k Golang : Join lines with certain suffix symbol example
+22k Golang : Use TLS version 1.2 and enforce server security configuration over client
+5.9k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error