Pcornel
Browse topics
Options
Recent
Favorites
Linux · Technical reference

Regular Expressions

Direct answer

Regular expressions describe text patterns: . any character, * + ? repetition, [] character sets, ^ $ anchors, () groups and | alternation. grep uses basic (BRE) by default, grep -E extended (ERE), grep -P Perl syntax.

When to use this

Use it to search or replace patterns in grep, sed, awk and many configuration files.

First 30 seconds

1. Write the pattern and quote it.

2. Test: grep -oE '<re>' <sample> — matches only what you want?

3. Anchor with ^/$ to avoid partial matches.

4. Escape literal dots: \..

5. Apply to the full data.

Operational verification

pattern written and quoted → engine (BRE/ERE/PCRE) matches → only intended text matched → used for search or replace

Evidence · next step

For Text Processing → Regular Expressions, continue with the first unproven Topic check: Identify tool, regex mode/dialect and locale before interpreting metacharacters or character classes. If that boundary is healthy, advance to the adjacent check: Inspect the exact pattern after shell quoting/variable expansion and test it against known-match and known-nonmatch fixtures. Preserve the same host/time/identity scope and rerun the original workload before accepting recovery.

Continue only after interpreting the current observation.
Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
linux
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

Platformlinux
Scope / prerequisiteUse it to search or replace patterns in grep, sed, awk and many configuration files.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

5 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 Operational evidence path Verify boundary

shell source text → quote/escape/parameter expansion → regex engine + dialect/locale → pattern compilation → candidate record → match spans/captures → selected/transformed output → downstream action

Healthy evidence: pattern behavior is verified under the exact tool/dialect/locale against positive, negative and boundary fixtures, with the shell-delivered pattern matching intent.

Step 2 Verification and output interpretation Verify boundary

Existing fast checks for this Topic. - Identify tool, regex mode/dialect and locale before interpreting metacharacters or character classes.

  • Inspect the exact pattern after shell quoting/variable expansion and test it against known-match and known-nonmatch fixtures.
  • Use anchors/boundaries and explicit classes where accidental substring matches would be dangerous.
  • Compare match counts/samples to the expected oracle before using regex output in deletion, permissions, automation or security decisions.

Verification chain. shell source text → quote/escape/parameter expansion → regex engine + dialect/locale → pattern compilation → candidate record → match spans/captures → selected/transformed output → downstream action

Step 3 Commands Verify boundary
grep -E '^[0-9]{1,3}(\.[0-9]{1,3}){3}$' ips.txt
grep -P '\d+' file
Step 4 Failure modes and next checks Narrow the fault

Suspicious evidence: the regex accidentally matches substrings, changes behavior between BRE/ERE/PCRE, or shell escaping alters the pattern before matching.

Step 5 Common mistakes Narrow the fault
  • Mixing basic, extended and Perl regex syntax.
Evidence references

Evidence · 1 on this Topic

Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.

observation · 1
Key points

Anchor patterns (^error) to avoid false matches. In BRE, + ? | ( ) need a backslash — use -E instead. Quote regexes in single quotes so the shell does not expand them. Test on a small sample.

Key checks
  • grep -E '^[0-9]{1,3}(\.[0-9]{1,3}){3}$' <file> — example: IPv4-looking lines
  • grep -o '<regex>' <file> — only the matched part
  • grep -c '<regex>' <file> — count matching lines
  • sed -E 's/<re>/<repl>/g' <file> — replace with extended regex
ReferenceWhat it is1 section · depth on demand

Core model

First identify the regex engine/dialect actually used: POSIX BRE, POSIX ERE, PCRE-compatible modes or tool-specific variants. Then separate shell parsing from regex parsing, test against positive and negative fixtures, and anchor or bound the pattern so it matches exactly the intended records.

ReferenceImportant terms & boundaries5 sections · depth on demand

What this shows and what it does not

Regex verification shows only the defined pattern over the tested input/dialect, but it does not show business meaning or safe coverage outside those fixtures.

In depth

Regular expressions: basic, extended and the differences that matter

Regular expressions describe text patterns for grep, sed, awk, find, editors and many configuration files. The regex(7) manual page describes the POSIX forms used by the classic tools:

  • Basic regular expressions (BRE), the default in grep and sed, treat ?, +, {, | and ( as literal characters. They need a backslash (\{, \() to act as operators, and GNU tools add \+, \? and \|.
  • Extended regular expressions (ERE), with grep -E, sed -E and awk, use these characters as operators directly.
  • When several matches start at the same position, POSIX matching takes the longest one.
  • Bracket expressions can use named classes such as [[:digit:]], [[:alpha:]] and [[:space:]].
  • Back-references (\1) are only defined for BREs.

Building blocks

ElementMeaning
.Any one character
[abc], [^abc], [a-z]One of / none of / a range
[[:digit:]], [[:space:]]Named classes (independent of locale ordering)
^, $Start / end of line
*Zero or more of the preceding item
+, ? (ERE)One or more / zero or one
{n,m} (ERE) / \{n,m\} (BRE)Between n and m repetitions
a|b (ERE)Alternation
( ) (ERE) / \( \) (BRE)Grouping

The same pattern in BRE and ERE

GoalBRE (grep, sed)ERE (grep -E, sed -E, awk)
Three digits[0-9]\{3\}[0-9]{3}
"error" or "fail"error\|fail (GNU)error|fail
One or more spaces * or \+ (GNU) +
Capture and reuse\(..\)\1Back-references aren't POSIX ERE

Other dialects

Perl-compatible expressions (PCRE), used by grep -P, most programming languages and many applications, add \d, \w, \s, lazy quantifiers (*?) and look-around. They don't exist in POSIX BRE or ERE. \d in plain grep -E doesn't mean "digit".

host$ grep -E '^[0-9]{1,3}(\.[0-9]{1,3}){3}$' addresses.txt
host$ grep -nE 'error|fail(ed|ure)?' /var/log/app/api.log | head -3
host$ grep -Eo 'user=[[:alnum:]_.-]+' /var/log/auth-app.log | sort | uniq -c | sort -rn | head
host$ sed -E 's/^([^=]+)=(.*)$/\1 = "\2"/' settings.env
host$ grep -c '\d\+' numbers.txt; grep -cE '[0-9]+' numbers.txt
0
42
host$ grep -P '(?<=id=)\d+' requests.log | head -2

Reading the last test

The first count is 0 because, outside PCRE, \d doesn't mean "digit". The bracket form [0-9] (or [[:digit:]]) works in every POSIX tool. Note too that the address pattern accepts 999.999.999.999. Regular expressions check shape, not meaning, so validate values in code where it matters.

Documented example, not captured output.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

How it works at runtime

Regular Expressions is part of Text Processing → Regular Expressions. Regular Expressions defines pattern matching used by Linux text tools, with emphasis on dialect, anchoring, character classes, repetition, alternation, grouping and shell-quoting boundaries.

Topic-specific state model. Regular Expressions defines pattern matching used by Linux text tools, with emphasis on dialect, anchoring, character classes, repetition, alternation, grouping and shell-quoting boundaries.

Interpretation rule. - Basic and extended regular expressions ≠ identical syntax; metacharacters such as parentheses, plus and alternation can change meaning by dialect.

  • A regex match ≠ whole-line or whole-field match unless anchoring/boundaries enforce it.
  • Shell quoting/escaping ≠ regex escaping; the pattern must survive shell parsing before the regex engine sees it.
  • Successful match against examples ≠ safe selection against unseen edge cases or catastrophic overmatching.

Quick reference

Regular expression flavours on Linux:

FlavourToolsExample
BRE (basic)grep, sedgrep 'ab\{2,\}' (escaped braces)
ERE (extended)grep -E, sed -E, awkgrep -E 'ab{2,}'
PCREgrep -P, rg, Perl, Pythongrep -P '\d{3}(?=px)'

Useful patterns:

grep -E '^[0-9]{1,3}(\.[0-9]{1,3}){3}' file          # IPv4-like
grep -Ev '^\s*(#|$)' /etc/ssh/sshd_config            # strip comments/blank
sed -E 's/(user=)[^ ]+/\1REDACTED/g' log
grep -o 'status=[0-9]+' log | sort | uniq -c

Quote patterns in single quotes so the shell does not expand *, $ or \.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

Limits and how it fails

Primary failure point. Regex verification shows only the defined pattern over the tested input/dialect, but it does not show business meaning or safe coverage outside those fixtures.

ReferenceConfiguration & state1 section · depth on demand

Configuration, persistence and lifecycle

Distribution/platform context. Text Processing owns the surrounding tool/pipeline; Shell & Bash owns shell quoting/expansion; this Topic owns regex grammar and match boundaries.

Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor doclinux current

Authoritative/upstream documentation reviewed for bounded claims in Text Processing → Regular Expressions. Documentation verification only; this is not observed lab or production Evidence.

Basis: https://www.gnu.org/software/coreutils/manual/coreutils.html · confidence 94%
Technical changelog & impact

What changed and what may be affected

Recent technical edits are separated from ordinary page timestamps. Relationship impact is advisory: it identifies nearby canonical references to review, not automatic breakage.

Related reference impactReview these references after material technical changes when their shared boundary is affected.
Terminology layer

Terms & aliases

Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.

Aliases that resolve here
linux regexregular expressions grepposix bre eregrep regex
Embedded reference data

Quick lookup tables

Regular Expressions operational reference

Topic-specific lookup boundaries, proof limits and next-step Evidence for Regular Expressions.

Lookup boundaryTopic-specific referenceOperational use
Scope / effective stateRegular Expressions defines pattern matching used by Linux text tools, with emphasis on dialect, anchoring, character classes, repetition, alternation, grouping and shell-quoting boundaries.Establish exactly what this Topic owns before crossing into another subsystem.
Fast verificationPin host/distribution + shell/version/mode → identify cwd/mount namespace + input/path/stream → preserve quoting/expansion and final argv → map fd/pipeline/process boundaries → inspect object/variable/status/signal state → make one minimal reversible change → read back effective state → repeat original consumer/script/workload test.Use the shortest evidence path first; a fast check is a boundary test, not blanket proof.
Verification chainshell source text → quote/escape/parameter expansion → regex engine + dialect/locale → pattern compilation → candidate record → match spans/captures → selected/transformed output → downstream actionTrace requested/configured state through effective state to the observed workload result.
Failure boundaryRegex verification proves only the defined pattern over the tested input/dialect; it does not prove business meaning or safe coverage outside those fixtures.Stop broad troubleshooting at the first boundary that is not supported by evidence.
Positive evidenceCorrelated Linux file/text/shell evidence can establish this proof path: shell source text → quote/escape/parameter expansion → regex engine + dialect/locale → pattern compilation → candidate record → match spans/captures → selected/transformed output → downstream actionUse this observation only for the specific claim it actually supports.
Evidence limitIt does not independently prove behavior outside the captured host, shell/session, cwd/namespace, input, process, filesystem, locale, time or workload scope. Regex verification proves only the defined pattern over the tested input/dialect; it does not prove business meaning or safe coverage outside those fixtures.Do not promote a local success signal into end-to-end or adjacent-dependency proof.
Next troubleshooting checkContinue from the first unproven boundary: capture the exact shell-delivered argv/streams or resolved object, verify the effective target state, change only the demonstrated cause, then repeat the original consumer/script/workload and adjacent regression checks.Continue to the next unresolved boundary while preserving the original test condition.

Regular Expressions · operational reference

Compact Linux state, persistence, verification and boundary reference for fast lookup.

Reference boundaryRegular Expressions
Topic pathText Processing → Regular Expressions
Runtime stateRegular Expressions defines pattern matching used by Linux text tools, with emphasis on dialect, anchoring, character classes, repetition, alternation, grouping and shell-quoting boundaries.
Fast checks- Identify tool, regex mode/dialect and locale before interpreting metacharacters or character classes. - Inspect the exact pattern after shell quoting/variable expansion and test it against known-match and known-nonmatch fixtures. - Use anchors/boundaries and explicit classes where accidental substring matches would be dangerous. - Compare match counts/samples to the expected oracle before using regex output in deletion, permissions, automation or security decisions.
Verification chainshell source text → quote/escape/parameter expansion → regex engine + dialect/locale → pattern compilation → candidate record → match spans/captures → selected/transformed output → downstream action Boundary chain: local authoritative state → adjacent dependency → effective/programmed state → original workload/request → return/regression → explicit Evidence boundary. Boundary chain: local authoritative state → adjacent dependency → effective/programmed state → original workload/request → return path or regression → explicit Evidence boundary.
Failure boundaryRegex verification proves only the defined pattern over the tested input/dialect; it does not prove business meaning or safe coverage outside those fixtures. Boundary chain: process/context → userspace configuration → kernel subsystem/resource → device/network/filesystem dependency → effective state → original workload.
Persistence ruleProve which configuration source owns the state, then prove that the running consumer loaded or generated the intended state.
Confirmation

Confirm action

Continue?