Regexp Replace Substring Pattern Match
Clean text with regexp_replace masking, substring FROM pattern extraction, and the ~ operator for regex membership tests inside SELECT lists.
Code
WITH raw_contacts(id, note) AS (
VALUES
(1, 'call Ada at 010-1234-5678 tomorrow'),
(2, 'backup number 13900001111'),
(3, 'no phone here')
)
SELECT
id,
-- regexp_replace 脱敏:把整段手机号换掉,[0-9] 是 POSIX 数字类,g 表示全部替换
regexp_replace(note, '[0-9]{3}-[0-9]{4}-[0-9]{4}', 'XXX-XXXX-XXXX', 'g') AS masked,
-- substring FROM pattern:提取第一个匹配的捕获串,没有匹配得 NULL
substring(note FROM '[0-9]{11}') AS mobile11,
-- ~ 操作符做正则判定,返回 boolean
(note ~ 'call .* at') AS has_call
FROM raw_contacts
ORDER BY id;
-- regexp 系列都是普通标量函数,在 SELECT/WHERE/UPDATE 里随处可用How the snippet works
What runs is SELECT, with raw_contacts as the object involved.
Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; an ORDER BY that fixes the output order.
Applying it
The raw_contacts table is the working surface here.
Interactive Tools for This Topic
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.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.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.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- What are the relations in play here?
- The references are `raw_contacts`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.