Go (RE2)

Private IP Address (RFC 1918) in GO

Match IPv4 addresses in the RFC 1918 private ranges: 10/8, 192.168/16, and 172.16/12.

Try it in the GO tester →

Pattern

regexGO
\b(?:10(?:\.\d{1,3}){3}|192\.168(?:\.\d{1,3}){2}|172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2})\b   (flags: g)

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`\b(?:10(?:\.\d{1,3}){3}|192\.168(?:\.\d{1,3}){2}|172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2})\b`)
	input := `Servers at 10.0.0.5 and 192.168.1.20`
	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

Three top-level alternatives cover the three reserved private ranges. 10(?:\.\d{1,3}){3} matches 10.x.x.x. 192\.168(?:\.\d{1,3}){2} matches 192.168.x.x. 172\.(?:1[6-9]|2\d|3[01]) constrains the second octet to the 16–31 sub-range, then (?:\.\d{1,3}){2} matches the last two octets. \b boundaries prevent partial-IP matches inside longer numbers.

Examples

Input

Servers at 10.0.0.5 and 192.168.1.20

Matches

  • 10.0.0.5
  • 192.168.1.20

Input

172.16.50.1 is private; 172.32.0.1 is not

Matches

  • 172.16.50.1

Input

Public IP 8.8.8.8

No match

Same pattern, other engines

← Back to Private IP Address (RFC 1918) overview (all engines)