Regex Matching with =~ Operator
Uses Bash regex matching with the =~ operator for pattern validation, extraction, and conditional logic including email, IP, and URL validation.
Code
#!/usr/bin/env bash
set -euo pipefail
# Email validation
validate_email() {
local email=$1
local regex="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
if [[ "$email" =~ $regex ]]; then
echo "Valid email: $email"
return 0
else
echo "Invalid email: $email"
return 1
fi
}
# IP address validation
validate_ip() {
local ip=$1
local regex="^([0-9]{1,3}\.){3}[0-9]{1,3}$"
if [[ "$ip" =~ $regex ]]; then
IFS="." read -ra octets <<< "$ip"
for octet in "${octets[@]}"; do
(( octet > 255 )) && return 1
done
echo "Valid IP: $ip"
return 0
fi
echo "Invalid IP: $ip"
return 1
}
# URL parsing
parse_url() {
local url=$1
local regex="^(https?)://([^/:]+)(:([0-9]+))?(/.*)?$"
if [[ "$url" =~ $regex ]]; then
echo "Protocol: ${BASH_REMATCH[1]}"
echo "Host: ${BASH_REMATCH[2]}"
echo "Port: ${BASH_REMATCH[4]:-default}"
echo "Path: ${BASH_REMATCH[5]:-/}"
else
echo "Invalid URL: $url"
fi
}
# Version number extraction
extract_version() {
local str=$1
local regex="([0-9]+)\.([0-9]+)\.([0-9]+)"
if [[ "$str" =~ $regex ]]; then
echo "Major: ${BASH_REMATCH[1]}"
echo "Minor: ${BASH_REMATCH[2]}"
echo "Patch: ${BASH_REMATCH[3]}"
fi
}
# Test validations
echo "=== Email Validation ==="
validate_email "[email protected]"
validate_email "invalid-email"
echo "=== IP Validation ==="
validate_ip "192.168.1.1"
validate_ip "256.1.1.1"
echo "=== URL Parsing ==="
parse_url "https://example.com:8080/api/v1"
parse_url "http://localhost/path"
echo "=== Version Extraction ==="
extract_version "Version 2.5.3 released"Bash regex matching uses [[ "$string" =~ $regex ]]. BASH_REMATCH[0] contains the full match, BASH_REMATCH[1..N] contain captured groups. Regex uses ERE (Extended Regular Expressions) - no \d or \w, use [0-9] and [a-zA-Z0-9_]. Do not quote the regex variable to prevent escaping issues. Regex is useful for input validation without external tools.
Interactive Tools for This Topic
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
Report a problem with this exampleOpens a pre-filled issue on GitHub.