mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4mobile wallpaper 5mobile wallpaper 6
694 words
3 minutes
Glob and Regex Cheatsheet
2026-03-15
统计加载中...

There are two common pattern-matching systems: glob and regular expressions (regex). Glob is simpler and primarily used for filename matching, while regex is more expressive and used for matching, extracting, and replacing text content.

Glob (Wildcard)#

Glob patterns are used for filename matching in shell commands such as ls, cp, and rm. They are simpler than regex, but still powerful for day-to-day file operations.

Pattern/SymbolMeaningExampleNotes
BASIC WILDCARDS
*Matches zero or more characters*.txt -> file.txt, a.txtDoes not match hidden files (.bashrc)
?Matches exactly one character?.txt -> a.txt, 1.txtab.txt will not match
[list]Matches any single character in list[ab].txt -> a.txt, b.txtc.txt will not match
[!list]Matches any single character NOT in list[!a].txt -> b.txt, c.txta.txt will not match
[c1-c2]Matches any single character in range[0-9].txt -> 0.txt to 9.txtFollows ASCII order
POSIX CLASSESMust be used inside [], e.g. [[:digit:]]
[:alnum:]Alphanumeric characters*[[:alnum:]]*Equivalent to [a-zA-Z0-9]
[:alpha:]Alphabetic characters[[:alpha:]]*.txtEquivalent to [a-zA-Z]
[:digit:]Numeric digitslog[[:digit:]].txtEquivalent to [0-9]
[:lower:]Lowercase letters[[:lower:]]*.shEquivalent to [a-z]
[:upper:]Uppercase letters[[:upper:]]*Equivalent to [A-Z]
[:space:]Whitespace charactersUseful for text processingSpace, tab, newline, etc.
BRACE EXPANSIONExpansion, not pattern matching
{a,b,c}Comma-separated alternativestouch {a,b,c}.txtCreates a.txt, b.txt, c.txt
{1..5}Numeric sequencemkdir folder_{1..5}Creates folder_1 to folder_5
{a..z}Alphabetic sequenceecho {a..c}Outputs a b c
{,.bak}Shorthand suffix expansioncp config.ini{,.bak}Same as cp config.ini config.ini.bak
EXTENDED GLOB (Bash)Requires shopt -s extglob
?(pattern)Matches zero or one occurrencefile?(s).txtMatches file.txt, files.txt
*(pattern)Matches zero or more occurrencesfile*(s).txtMatches file.txt, filessss.txt
+(pattern)Matches one or more occurrencesfile+(s).txtMatches files.txt (not file.txt)
@(pattern)Matches exactly one occurrencefile@(a|b).txtMatches filea.txt, fileb.txt
!(pattern)Matches anything except pattern!(*.jpg|*.png)All files except .jpg and .png

Quick Examples:

# Basic wildcards
ls log* # All files starting with 'log'
ls log? # 'log' + exactly one character
ls log[123].txt # log1.txt, log2.txt, log3.txt
ls [!abc]* # Files NOT starting with a, b, or c
# POSIX character classes
ls *[[:digit:]]* # Files containing digits
ls [[:lower:]]*.txt # Files starting with lowercase
# Brace expansion
touch file_{1..10}.txt # Create file_1.txt to file_10.txt
cp config.ini{,.backup} # Backup config.ini
# Extended glob (enable first: shopt -s extglob)
rm !(*.jpg|*.png) # Delete all except images
ls file?(s).txt # Match with optional 's'

Glob Gotchas#

  • Hidden files: * does not match dotfiles by default; use .* explicitly.
  • Path separator: Wildcards do not cross /. Use */* or ** (with shopt -s globstar).
  • Shell expansion: The shell expands wildcards before passing args to commands.
  • Quote protection: Quote wildcards when passing patterns as literals, e.g. find . -name "*.txt".
  • Case sensitivity: Matching is case-sensitive by default; use shopt -s nocaseglob if needed.

Regex (Regular Expression)#

Regex is the “surgical knife” for text matching, extraction, and replacement. Unlike glob, regex is designed for content patterns inside strings, not filename expansion.

Regex consists of two building blocks:

  • Literal characters: match themselves, e.g. a matches a.
  • Metacharacters: symbols with special meaning, e.g. . matches almost any single character.
Pattern/SymbolMeaningExample PatternNotes / Typical Matches
BASIC MATCHING
a, cat, 2026Literal matchcatMatches exact text cat
.Any single character except newline (usually)b.gbag, big, b0g
\.Escape metacharacter\.comMatches literal .com
[abc]Any one character in set[bt]agbag, tag
[^abc]Any one character not in set[^b]agtag, cag (not bag)
[a-z], [0-9]Character range[A-F0-9]One hex-like character
QUANTIFIERSQuantifiers apply to the token immediately on the left
*0 or moreab*a, ab, abbb
+1 or moreab+ab, abbb (not a)
?0 or 1 (optional)colou?rcolor, colour
{n}Exactly na{3}aaa
{n,}At least na{2,}aa, aaa, …
{n,m}Between n and ma{2,4}aa, aaa, aaaa
*?, +?, {n,m}?Non-greedy (lazy) quantifiers<.*?>Matches the shortest tag-like segment
ANCHORS & BOUNDARIESRestrict where matching can happen
^Start of line/string^HelloMatches lines starting with Hello
$End of line/stringdone$Matches lines ending with done
\bWord boundary\bhi\bMatches standalone hi, not high
\BNot a word boundary\Bend\BCan match internal end in bendable
\A, \ZAbsolute start/end (engine-dependent)\AINFO:.*\ZUseful when ^/$ behavior changes in multiline mode
PREDEFINED CLASSESCommon shorthand classes
\d / \DDigit / non-digit\d{4}2026
\w / \WWord char / non-word\w+letters, digits, underscore
\s / \SWhitespace / non-whitespace\s+spaces, tabs, newlines
GROUPING & BRANCHINGBuild larger matching logic
(abc)Capturing group(ab)+Repeats ab as a group
(?:abc)Non-capturing group(?:cat|dog)s?Group structure without storing capture
(a|b|c)Alternation (or)cat|dogMatches cat or dog
\1, \2Backreference to captured group(\w+)\s+\1Matches repeated word, e.g. go go
LOOKAROUNDSAssert context without consuming characters
(?=...)Positive lookahead\w+(?=:)Word before :
(?!...)Negative lookaheadfoo(?!bar)foo not followed by bar
(?<=...)Positive lookbehind(?<=\$)\d+Number after $
(?<!...)Negative lookbehind(?<!-)\d+Number not prefixed by -
EMPTY / BLANK MATCHINGUseful for cleanup and empty-line checks
^$Empty line (no character at all)^$Matches truly blank lines
^\s*$Blank or whitespace-only line^\s*$Matches empty lines, spaces-only, tabs-only
^\s+|\s+$Leading or trailing whitespace^\s+|\s+$Common in trim replacement patterns

Quick Examples:

  • bash examples
# grep -P uses PCRE (if your grep supports -P)
grep -P '^\d{4}-\d{2}-\d{2}$' dates.txt # ISO date: 2026-03-15
grep -P '^\s*$' notes.txt # Empty or whitespace-only lines
grep -P '\b(error|warn|fatal)\b' app.log # Any of error/warn/fatal
  • javascript examples
// Extract duplicated words: "go go", "yes yes"
const re = /(\w+)\s+\1/g;
"go go stop".match(re); // ["go go"]
// Trim via regex replacement
" hello ".replace(/^\s+|\s+$/g, ""); // "hello"

Regex Gotchas#

  • Engine differences: JS, Python, PCRE, and Java differ in lookbehind support, Unicode behavior, and flags.
  • Greedy by default: .* consumes as much as possible; use .*? for shortest matches.
  • Escaping layers: Inside strings, you often need double escaping, e.g. "\\d+".
  • Multiline vs singleline: m affects ^/$; s allows . to match newline.
  • Performance pitfalls: Nested quantifiers can cause catastrophic backtracking.
  • Python tip: Prefer raw strings like r"\d+" to avoid accidental escapes.
Share

If this article helped you, please share it with others!

Glob and Regex Cheatsheet
https://yur1ka.netlify.app/posts/26_03_12_regex/
Author
FuFu
Published at
2026-03-15
License
Unlicensed

Some information may be outdated

Cover
Sample Song
Sample Artist
Cover
Sample Song
Sample Artist
0:00 / 0:00