regex

package
v0.9.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 30, 2026 License: MIT Imports: 3 Imported by: 0

README

GoZod Regular Expressions

A collection of common regular expressions for Go, ported from TypeScript Zod v4 regexes.

Usage Example

package main

import (
	"fmt"
	"regexp"
	"github.com/kaptinlin/gozod/pkg/regex"
)

func main() {
	// Validate a UUID v4
	if regexes.UUID4.MatchString("f47ac10b-58cc-4372-a567-0e02b2c3d479") {
		fmt.Println("Valid UUID4")
	}
	
	// Validate an email using practical email pattern
	if regexes.Email.MatchString("user@example.com") {
		fmt.Println("Valid email")
	}
	
	// Validate IPv4 address
	if regexes.IPv4.MatchString("192.168.1.1") {
		fmt.Println("Valid IPv4 address")
	}
	
	// Create a length-restricted string pattern
	customStr := regexes.StringRegex(3, 10)
	if customStr.MatchString("hello") {
		fmt.Println("String length is between 3 and 10")
	}
	
	// Check ISO 8601 date format
	if regexes.Date.MatchString("2024-03-15") {
		fmt.Println("Valid ISO 8601 date")
	}
	
	// Validate E.164 phone number
	if regexes.E164.MatchString("+1234567890") {
		fmt.Println("Valid E.164 phone number")
	}
}

Quick Reference

import (
	"regexp"
	"github.com/kaptinlin/gozod/pkg/regex"
)

// Identifiers
regexes.UUID4.MatchString(id)          // Validate UUID v4
regexes.CUID.MatchString(id)           // Validate CUID
regexes.NanoID.MatchString(id)         // Validate NanoID

// Networking
regexes.IPv4.MatchString("192.168.0.1")      // true
regexes.CIDRv4.MatchString("10.0.0.0/24")    // true

// Date & time (ISO-8601)
regexes.DateTime.MatchString("2024-06-12T08:04:00Z") // true
regexes.Date.MatchString("2024-03-15")              // true

// Custom length-restricted string
short := regexes.StringRegex(1, 5)
short.MatchString("four") // true

// Use pattern constants with regexp
hex32 := regexp.MustCompile(`^[0-9a-f]{32}$`)
hex32.MatchString("aabbccddeeff00112233445566778899")

API Cheat-Sheet

Category Patterns & Functions Notes
Identifiers UUID4 CUID NanoID ULID ... Unique IDs
Email Email Practical email validation
Networking IPv4 IPv6 CIDRv4 CIDRv6 IP & CIDR
Date & Time Date DateTime Time ISO-8601 formats
Encoding Base64 Base64URL Base64, URL-safe
Phone E164 E.164 phone numbers
Text Emoji JWT Emoji, JWT
URL URL URL validation
Utility StringRegex(min, max) Custom string length

Documentation

Overview

Package regex provides pre-compiled regular expressions for common data formats.

Key features:

  • Email patterns (Email, HTML5Email, RFC5322Email, UnicodeEmail)
  • URL patterns (URL)
  • Network patterns (IPv4, IPv6, CIDR, MAC)
  • Date/time patterns (Date, Time, Datetime, Duration)
  • ID formats (UUID, CUID, CUID2, ULID, NanoID, XID, KSUID)
  • Encoding patterns (Base64, Base64URL)
  • Primitives (String, Integer, Number, Boolean)

Usage:

if regex.Email.MatchString(email) {
    // valid email format
}

if regex.UUID.MatchString(uuid) {
    // valid UUID format
}

Index

Constants

This section is empty.

Variables

View Source
var (
	// Duration matches ISO 8601-1 duration format.
	// Matches P<weeks>W or P<years>Y<months>M<days>D(T<hours>H<minutes>M<seconds>S).
	Duration = regexp.MustCompile(`^P(?:(\d+W)|(\d+Y)?(\d+M)?(\d+D)?(?:T(\d+H)?(\d+M)?(\d+(?:[.,]\d+)?S)?)?)$`)

	// ExtendedDuration matches ISO 8601-2 extended duration format (simplified for Go).
	ExtendedDuration = regexp.MustCompile(`^[-+]?P(?:[-+]?\d+[.,]?\d*[YMWD])*(?:T(?:[-+]?\d+[.,]?\d*[HMS])*)?$`)
)

Duration patterns.

View Source
var (
	// Date matches ISO 8601 date format (YYYY-MM-DD) with leap year validation.
	Date = regexp.MustCompile(`^` + datePattern + `$`)

	// DefaultTime matches ISO 8601 time (HH:MM or HH:MM:SS with optional fractional seconds).
	DefaultTime = regexp.MustCompile(`^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?$`)

	// DefaultDatetime matches ISO 8601 datetime with Z or offset timezone.
	DefaultDatetime = regexp.MustCompile(`^` + datePattern + `T(?:` + timePattern(nil) + `(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d))$`)
)

Date and time patterns.

View Source
var (
	// Email provides practical email validation that rejects common invalid patterns.
	// Rejects IP-address domains, leading/trailing/consecutive dots, and domains without TLD.
	Email = regexp.MustCompile(`^[A-Za-z0-9_'+\-]+([A-Za-z0-9_'+\-]*\.[A-Za-z0-9_'+\-]+)*@[A-Za-z0-9]([A-Za-z0-9\-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9\-]*[A-Za-z0-9])?)*\.[A-Za-z]{2,}$`)

	// HTML5Email matches HTML5 input[type=email] validation per the WHATWG spec.
	HTML5Email = regexp.MustCompile(`^[a-zA-Z0-9.!#$%&'*+/=?^_` + "`" + `{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$`)

	// RFC5322Email matches RFC 5322-compliant email addresses.
	RFC5322Email = regexp.MustCompile(`^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$`)

	// UnicodeEmail matches emails allowing Unicode characters with length limits.
	UnicodeEmail = regexp.MustCompile(`^[^\s@"]{1,64}@[^\s@]{1,255}$`)

	// BrowserEmail is an alias for [HTML5Email] (identical pattern).
	BrowserEmail = HTML5Email
)
View Source
var (
	// Base64 matches standard Base64-encoded strings (RFC 4648).
	Base64 = regexp.MustCompile(`^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$`)

	// Base64URL matches URL-safe Base64 strings with optional padding.
	Base64URL = regexp.MustCompile(`^[A-Za-z0-9_-]*={0,2}$`)

	// Hex matches hexadecimal strings (any length including empty).
	Hex = regexp.MustCompile(`^[0-9a-fA-F]*$`)
)

Encoding format patterns.

View Source
var (
	// MD5Hex matches MD5 hashes in hexadecimal format (32 chars).
	MD5Hex = regexp.MustCompile(`^[0-9a-fA-F]{32}$`)

	// SHA1Hex matches SHA-1 hashes in hexadecimal format (40 chars).
	SHA1Hex = regexp.MustCompile(`^[0-9a-fA-F]{40}$`)

	// SHA256Hex matches SHA-256 hashes in hexadecimal format (64 chars).
	SHA256Hex = regexp.MustCompile(`^[0-9a-fA-F]{64}$`)

	// SHA384Hex matches SHA-384 hashes in hexadecimal format (96 chars).
	SHA384Hex = regexp.MustCompile(`^[0-9a-fA-F]{96}$`)

	// SHA512Hex matches SHA-512 hashes in hexadecimal format (128 chars).
	SHA512Hex = regexp.MustCompile(`^[0-9a-fA-F]{128}$`)
)

Hash format patterns.

View Source
var (
	// CUID matches strings in CUID format (starts with 'c' or 'C', 9+ chars).
	CUID = regexp.MustCompile(`^[cC][^\s-]{8,}$`)

	// CUID2 matches strings in CUID2 format (lowercase alphanumeric).
	CUID2 = regexp.MustCompile(`^[0-9a-z]+$`)

	// ULID matches strings in ULID format (26 Crockford Base32 chars).
	ULID = regexp.MustCompile(`^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$`)

	// XID matches strings in XID format (20 base32 chars).
	XID = regexp.MustCompile(`^[0-9a-vA-V]{20}$`)

	// KSUID matches strings in KSUID format (27 alphanumeric chars).
	KSUID = regexp.MustCompile(`^[A-Za-z0-9]{27}$`)

	// NanoID matches strings in NanoID format (21 URL-safe chars).
	NanoID = regexp.MustCompile(`^[a-zA-Z0-9_-]{21}$`)

	// GUID matches any UUID-like identifier with 8-4-4-4-12 hex pattern.
	GUID = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)

	// UUID matches RFC 4122 UUID (versions 1-8) or the nil UUID.
	UUID = regexp.MustCompile(`^(?:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$`)

	// UUID4 matches version 4 UUIDs.
	UUID4 = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$`)

	// UUID6 matches version 6 UUIDs.
	UUID6 = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-6[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$`)

	// UUID7 matches version 7 UUIDs.
	UUID7 = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-7[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$`)
)

ID format patterns.

View Source
var (
	// IPv4 matches IPv4 addresses (0.0.0.0 to 255.255.255.255).
	IPv4 = regexp.MustCompile(`^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$`)

	// IPv6 matches IPv6 addresses including compressed forms.
	IPv6 = regexp.MustCompile(`^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$`)

	// CIDRv4 matches IPv4 CIDR notation (e.g., "10.0.0.0/24").
	CIDRv4 = regexp.MustCompile(`^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$`)

	// CIDRv6 matches IPv6 CIDR notation (e.g., "2001:db8::/32").
	CIDRv6 = regexp.MustCompile(`^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$`)

	// IP matches any IP address (IPv4 or IPv6).
	IP = regexp.MustCompile(`((?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9]))|((?:(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|(?:[0-9a-fA-F]{1,4})?::(?:[0-9a-fA-F]{1,4}:?){0,6}))`)

	// Hostname matches valid DNS hostnames per RFC 1123.
	// Note: Go's regex lacks lookahead, so the 1-253 char length check must be done in validation code.
	Hostname = regexp.MustCompile(`^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$`)

	// Domain matches valid domain names with a TLD (e.g., "example.com").
	Domain = regexp.MustCompile(`^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`)

	// HTTPProtocol matches "http" or "https".
	HTTPProtocol = regexp.MustCompile(`^https?$`)
)

Network address patterns.

View Source
var (
	// String matches any string with no length restrictions.
	String = regexp.MustCompile(`^[\s\S]*$`)

	// Bigint matches big integers with optional trailing 'n' (e.g., "123n").
	Bigint = regexp.MustCompile(`^-?\d+n?$`)

	// Integer matches integers including negative numbers.
	Integer = regexp.MustCompile(`^-?\d+$`)

	// Number matches numbers including decimals and negative numbers.
	Number = regexp.MustCompile(`^-?\d+(?:\.\d+)?$`)

	// Boolean matches boolean values (case-insensitive).
	Boolean = regexp.MustCompile(`(?i)^(true|false)$`)

	// Null matches "null" (case-insensitive).
	Null = regexp.MustCompile(`(?i)^null$`)

	// Undefined matches "undefined" (case-insensitive).
	Undefined = regexp.MustCompile(`(?i)^undefined$`)

	// Lowercase matches strings containing no uppercase letters.
	Lowercase = regexp.MustCompile(`^[^A-Z]*$`)

	// Uppercase matches strings containing no lowercase letters.
	Uppercase = regexp.MustCompile(`^[^a-z]*$`)

	// JSONString matches any string (simplistic; actual validation should be done at runtime).
	// Uses the same pattern as String since runtime JSON parsing is required for real validation.
	JSONString = String
)

Primitive type patterns.

View Source
var (
	// URL matches valid URLs with common protocols (http, https, ftp, ws, file, etc.).
	URL = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*://[^\s/$.?#].[^\s]*$`)

	// HTTPURL matches URLs starting with http:// or https://.
	HTTPURL = regexp.MustCompile(`^https?://[^\s/$.?#].[^\s]*$`)
)
View Source
var E164 = regexp.MustCompile(`^\+[1-9]\d{6,14}$`)

E164 matches E.164 international phone numbers (e.g., "+14155552671").

View Source
var Emoji = regexp.MustCompile(`^[` +

	`\x{1F600}-\x{1F64F}` +
	`\x{1F300}-\x{1F5FF}` +
	`\x{1F680}-\x{1F6FF}` +
	`\x{1F700}-\x{1F77F}` +
	`\x{1F780}-\x{1F7FF}` +
	`\x{1F800}-\x{1F8FF}` +
	`\x{1F900}-\x{1F9FF}` +
	`\x{1FA00}-\x{1FA6F}` +
	`\x{1FA70}-\x{1FAFF}` +

	`\x{2600}-\x{26FF}` +
	`\x{2700}-\x{27BF}` +

	`\x{1F1E6}-\x{1F1FF}` +

	`\x{3000}-\x{303F}` +
	`\x{3200}-\x{32FF}` +

	`\x{1F004}` +
	`\x{1F0CF}` +
	`\x{1F18E}` +
	`\x{1F191}-\x{1F19A}` +
	`\x{1F201}` +
	`\x{1F21A}` +
	`\x{1F22F}` +
	`\x{1F232}-\x{1F236}` +
	`\x{1F238}-\x{1F23A}` +
	`\x{1F250}` +
	`\x{1F251}` +

	`\x{1F3FB}-\x{1F3FF}` +
	`\x{200D}` +
	`\x{FE0F}` +
	`]+$`)

Emoji matches emoji characters (Go-compatible implementation) Note: Go's regexp doesn't support Unicode properties like \p{Extended_Pictographic} This pattern covers comprehensive emoji ranges based on Unicode standards

View Source
var MACDefault = MAC(":")

MACDefault is the default MAC address regex using ":" as delimiter.

Functions

func Datetime

func Datetime(options DatetimeOptions) *regexp.Regexp

Datetime returns a regex for matching ISO 8601 datetime format.

func MAC

func MAC(delimiter string) *regexp.Regexp

MAC returns a cached regex for validating MAC addresses with the given delimiter. An empty delimiter defaults to ":".

MAC(":")  matches "00:1A:2B:3C:4D:5E" or "00:1a:2b:3c:4d:5e"
MAC("-")  matches "00-1A-2B-3C-4D-5E" or "00-1a-2b-3c-4d-5e"

func StringRegex

func StringRegex(min, max int) *regexp.Regexp

StringRegex returns a cached regex matching strings with length in [min, max]. A non-positive max means no upper bound.

func Time

func Time(opts TimeOptions) *regexp.Regexp

Time returns a regex for matching ISO 8601 time format.

func UUIDForVersion

func UUIDForVersion(version int) *regexp.Regexp

UUIDForVersion returns a regex matching a specific UUID version (1-8). For out-of-range versions, it returns the general UUID regex.

Types

type DatetimeOptions

type DatetimeOptions struct {
	// Precision specifies the number of decimal places for seconds.
	// nil: any number of decimal places; 0: no decimals; -1: minute precision only.
	Precision *int

	// Offset allows timezone offsets like +01:00 when true.
	Offset bool

	// Local makes the 'Z' timezone marker optional when true.
	Local bool
}

DatetimeOptions defines parameters for the datetime regex pattern.

type TimeOptions

type TimeOptions struct {
	// Precision specifies the number of decimal places for seconds.
	// nil: any number of decimal places; 0: no decimals; -1: minute precision only.
	Precision *int
}

TimeOptions defines parameters for the time regex pattern.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL