Go (RE2)

IP Address with CIDR Notation in GO

Match IPv4 addresses with CIDR prefix notation such as 10.0.0.0/8 or 192.168.1.0/24.

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?)\/(?:3[0-2]|[12]?\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?)\/(?:3[0-2]|[12]?\d)`)
	input := `10.0.0.0/8`
	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

The IPv4 portion uses alternation to strictly validate each octet in the 0–255 range (same as the standalone IPv4 pattern). \/(?:3[0-2]|[12]?\d) appends a / and a CIDR prefix constrained to 0–32.

Examples

Input

10.0.0.0/8

Matches

  • 10.0.0.0/8

Input

192.168.1.0/24

Matches

  • 192.168.1.0/24

Input

999.0.0.0/33

No match

Same pattern, other engines

← Back to IP Address with CIDR Notation overview (all engines)