Skip to content

Instantly share code, notes, and snippets.

@r6m
Last active December 30, 2017 11:05
Show Gist options
  • Save r6m/34ffcc6ef3608b4a3ec52bc6fa062b5c to your computer and use it in GitHub Desktop.
Save r6m/34ffcc6ef3608b4a3ec52bc6fa062b5c to your computer and use it in GitHub Desktop.
golang regex ip v4 & ip v6
package main
import(
"fmt"
"regexp"
)
const (
regexIPv4 = `(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})`
regexIPv6 = `((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*::((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*|((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4})){7}`
)
var str string = `this is a sample text with given 192.168.0.1 as an ip`
func main() {
re := regexp.MustCompile(regexIPv4)
// getting first match
// to get all matches use FindAllString(source, n)
ip := re.FindString(str)
fmt.Println(ip)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment