0xnhl

Regex

/ Update
3 min read

A regular expression, sometimes referred to as rational expression, is a sequence of characters that specifies a match pattern in text. Usually such patterns are used by string-searching algorithms for “find” or “find and replace” operations on strings, or for input validation.

Usage

  • re module in python.
  • grep -E <regex> <file>

Rules#

Literal and Meta Characters#

  • Literal characters: Ordinary letters and numbers match themselves directly (for example, /cat/ matches “cat”).
  • Meta characters: Special symbols control the pattern rules. Use a backslash (\) in front of a meta character to treat it as a normal literal (like \. to match an actual dot).

Character Classes (Sets)#

SymbolDescriptionExample Match
[...]Matches any single character inside the brackets[aeiou] matches any single vowel
-Matches a range of characters inside brackets[a-z] matches any lowercase letter
^Placed at the start inside brackets to match anything except those characters[^0-9] matches non-digits

Symbols for character types#

SymbolDescriptionExample Match
.Matches any character (letters, digits, symbols, spaces), except for a newline.c.t matches “cat”, “cot”, “c5t”
\dMatches any digit (0-9).In “ID_A17!”, matches 1,7
\Dmatches a non-digit (Alphabets, symbols)In “ID_A17!”, matches I,D,_,A,!
\wMatches any alphanumeric character (A-z, 0-9) OR an underscore (_).In “ID_A17!”, matches I,D,_,A,1,7
\WMatches a non-alphanumeric character (Symbols)In “ID_A17!”, matches !
\sMatches any single whitespace character (space, tab, newline).Matches the space in “user 1”.
\SMatches everything else (alphanumeric characters and symbols)
\Escapes a meta character to treat it as a literal.\. matches an actual dot ”.”

Symbols to quantify occurrences#

SymbolDescriptionExample
+One or more occurrences. (e.g., \d+ matches 1,12,12345).lo+ng matches “long”, “loong”
*Zero, one, or more occurrences.lo*ng matches “lng”, “long”, “loong”
?zero or one occurence (makes the item optional).favou?r matches “favor” or “favour”
{n}Exactly n occurrences.\d{4} matches four consecutive digits (e.g., 1234).
{n,n}Between m (minimum) and n (maximum) occurrences.\d{1,3} matches 1,12, or 123.

Anchors and Boundaries#

SymbolDescriptionExample
^Asserts the start of a string or line^Hello matches if “Hello” is at the beginning
$Asserts the end of a string or lineend$ matches if “end” is at the very end

Structural Rules#

  • Alternation (OR): (cat|dog) matches either “cat” or “dog”.
  • Capturing Groups: (\d{3}) matches three digits and saves them as a distinct group for extract or replacement.
  • Non-Capturing Groups: (?:cat|dog) groups the words together for matching without saving them into memory.
  • Word Boundary: \bcat\b matches the exact word “cat” but ignores “cat” inside “cacatua” or “bobcat”.

Common Regex patterns#

  • Alphanumeric Only: ^[a-zA-Z0-9]+$ restricts text to only letters and numbers.
  • Email Address: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
  • Phone Number (US format): ^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$
  • Date (YYYY-MM-DD): ^\d{4}-\d{2}-\d{2}$
  • URL: ^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$
  • Strip Whitespace: ^\s+|\s+$ matches leading or trailing spaces in a text string.
  • IPv4 Address: \b(?:(?:25[0-5]|2[0-4][0-3]|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4][0-3]|[01]?\d\d?)\b
  • MAC Address: ^[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(\1[0-9a-fA-F]{2}){4}$
  • Timestamp (ISO 8601): ^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$
  • Credit Card (Luhn-compliant placeholder): \b(?:\d{4}[ -]?){3}\d{4}\b
  • Standard Base64 Validation: ^[A-Za-z0-9+/]+={0,2}$
  • Base64 in a Text Stream/Log: \b[A-Za-z0-9+/]{4,}={0,2}\b
  • Strict Base64 Validation with length multiple of 4: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
Regex
https://nahil.xyz/vault/basics/regex/
AuthorNahil Rasheed
Published atJune 15, 2025
CopyrightCC BY 4.0
DisclaimerThis content is provided strictly for educational purposes only.