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
Match one of several patterns
rg 'warn|error' logs/

# Search for either of two words.

Match whole words only
rg '\bselect\b' docs/

# Avoid partial matches inside larger identifiers.

Match numeric fragments
rg '\b\d{3}\b' .

# Find three-digit numeric sequences.

Use capture groups in patterns
rg '(GET|POST|PUT|DELETE) /api/' server.log

# Group pieces of a regex for readability or PCRE2 replacements.

Show non-matching lines
rg -v '^#' .env.example

# Return the lines that do not match the pattern.

## PCRE2 features
Use the PCRE2 engine
rg -P '(?<=Authorization: )Bearer\s+\S+' headers.txt

# Turn on advanced regex features such as look-around.

Use a backreference
rg -P '\b(\w+)\s+\1\b' notes.txt

# Match repeated text with PCRE2.

Use look-ahead assertions
rg -P 'token(?==)' .env

# Match only when text is followed by another fragment.

Use Unicode-aware classes
rg '\p{L}+' docs/

# Search for letters with Unicode-aware semantics.

Search across line boundaries
rg -U 'foo
bar' sample.txt

# Allow regexes to match newlines.

Recommended next

No recommendations yet.