IPv4 Address in GO
Match valid IPv4 addresses with each octet constrained to 0–255.
Try it in the GO tester →Pattern
regexGO
(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?) (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)`)
input := `192.168.1.1`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
How the pattern works
Each octet alternation covers 250-255, 200-249, and 0-199 ranges to ensure strict 0-255 validity. Three octets with dots are matched, then the final octet.
Examples
Input
192.168.1.1Matches
192.168.1.1
Input
255.255.255.0Matches
255.255.255.0
Input
999.999.999.999No match
—