regexp_replace Masks Digits And Trims
regexp_replace rewrites text with anchored patterns and masks digit runs; without the g flag only the first occurrence ever changes.
Code
WITH notes AS (
SELECT * FROM (VALUES
(' Call 555-0100 tomorrow! '),
('Order #8841 shipped 2026-11-21')
) AS t(note)
)
SELECT
note,
-- trim leading whitespace: ^ anchors the start only
regexp_replace(note, '^\s+', '') AS trimmed,
-- mask every digit run as # before the text may enter logs
regexp_replace(note, '\d+', '#', 'g') AS masked,
-- digits only: phone-number extraction
regexp_replace(note, '\D', '', 'g') AS digits_only,
-- without the g flag only the first match changes
regexp_replace(note, '\s+', ' ') AS first_only
FROM notes;What the demo masks
Two notes run through four rewrites. The anchored trim removes the leading spaces of the first note; the g-flagged digit mask collapses every digit run into a single #, so 555-0100 prints #-# and the order line’s date prints #-#-#.
The \D pattern with g deletes every non-digit, leaving pure digit strings for extraction, 5550100 and 884120261121. The last column omits g on the whitespace pattern: only the first whitespace collapses, which is the visible difference a missing flag makes.
Practical notes
- Anchors and flags change scope, not the pattern itself.
- Mask before logging; extraction and masking are different goals.
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- What changes when the g flag is dropped?
- Only the first match is rewritten: the last column of the demo collapses the first whitespace run but leaves later ones, exactly the difference g makes.
Report a problem with this exampleOpens a pre-filled issue on GitHub.