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
+5.2k Golang : How to solve "too many .rsrc sections" error?
+6k Linux : How to fix Brother HL-1110 printing blank page problem
+29.9k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+11k Android Studio : Highlight ImageButton when pressed on example
+24.2k Golang : How to read integer value from standard input ?
+8.6k Golang : Validate IPv6 example
+6k Golang : Fibonacci number generator examples
+18.2k Golang : Delete item from slice based on index/key position
+4.8k nginx : force all pages to be SSL
+25.7k Golang : Find files by name - cross platform example
+8.1k Random number generation with crypto/rand in Go
+3.9k PHP : Extract part of a string starting from the middle