运行说明
两条笔记过四种改写。锚定 trim 去掉第一条的前导空格;带 g 的数字掩码把每段数字整体换成一个 #——555-0100 打印 #-#,订单行的日期打印 #-#-#。
\D 加 g 删除所有非数字,留下纯数字串供提取——5550100 与 884120261121。最后一列对空白模式不加 g:只有第一处空白折叠——这正是缺 g 标志的可见差别。
要点提示
- 锚与标志改变作用范围,不改模式本身。
- 进日志前先掩码;提取与掩码是两个目标。
核心语句
regexp_replace(note, '\d+', '#', 'g') AS masked
代码示例
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;