Last active
December 30, 2017 11:05
-
-
Save r6m/34ffcc6ef3608b4a3ec52bc6fa062b5c to your computer and use it in GitHub Desktop.
golang regex ip v4 & ip v6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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