Regex and Fixed Strings

Use basic regex, PCRE2, word boundaries, alternation, and literal searches with ripgrep.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

Regex basics

Common regex patterns that appear in real code and logs.

Match one of several patterns

Search for either of two words.

bashANYripgrepregexalternation
bash
rg 'warn|error' logs/
Notes

Alternation is often the fastest way to combine related searches into one pass.

Match whole words only

Avoid partial matches inside larger identifiers.

bashANYripgrepregexword-boundary
bash
rg '\bselect\b' docs/
Notes

Word boundaries are essential when searching SQL, config keys, or language keywords.

Match numeric fragments

Find three-digit numeric sequences.

bashANYripgrepregexdigits
bash
rg '\b\d{3}\b' .
Notes

Handy for HTTP status codes, IDs, and validation rules.

Use capture groups in patterns

Group pieces of a regex for readability or PCRE2 replacements.

bashANYripgrepregexgroups
bash
rg '(GET|POST|PUT|DELETE) /api/' server.log
Notes

Even when not replacing, capture groups make complex patterns easier to reason about.

Show non-matching lines

Return the lines that do not match the pattern.

bashANYripgrepinvert-match
bash
rg -v '^#' .env.example
Notes

Great for removing comments or blank-line noise in quick inspections.

PCRE2 features

Enable features beyond ripgrep's default regex engine when needed.

Use the PCRE2 engine

Turn on advanced regex features such as look-around.

bashANYripgreppcre2
bash
rg -P '(?<=Authorization: )Bearer\s+\S+' headers.txt
Notes

PCRE2 is especially useful for look-behind, backreferences, and some complex matching scenarios.

Use a backreference

Match repeated text with PCRE2.

bashANYripgreppcre2backreference
bash
rg -P '\b(\w+)\s+\1\b' notes.txt
Notes

Backreferences are not supported by the default regex engine, so `-P` is required.

Use look-ahead assertions

Match only when text is followed by another fragment.

bashANYripgreppcre2lookahead
bash
rg -P 'token(?==)' .env
Notes

Look-ahead helps when you want to match a token without consuming surrounding syntax.

Use Unicode-aware classes

Search for letters with Unicode-aware semantics.

bashANYripgrepunicoderegex
bash
rg '\p{L}+' docs/
Notes

Useful for multilingual repos and documentation sets.

Search across line boundaries

Allow regexes to match newlines.

bashANYripgrepmultiline
bash
rg -U 'foo
bar' sample.txt
Notes

`-U` disables the line-based restriction so patterns can span lines; combine with care because it can increase work and output size.

Recommended next

No recommendations yet.