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.

SqlSecurity Boundaries

Code

snippet
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

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.