Regexp Count, Like And Substr Functions
Postgres 15 regexp functions split the work: regexp_count tallies hits, regexp_substr grabs the nth match, regexp_instr locates it, regexp_like decides.
Code
-- PG15 的正则函数一族:计数、取值、定位、布尔判断各自一步到位
SELECT
-- 出现次数
regexp_count('2026-01-15, 2026-02-03, 2026-03-09', '\d{4}-\d{2}-\d{2}') AS date_hits,
-- 第 n 个匹配的原文:start 与 N 参数免掉手工偏移循环
regexp_substr('user=42, user=7, user=99', 'user=\d+', 1, 3) AS third_match,
-- 匹配起点配合 substr 截取错误码
substr('ERROR 0x1F at line 402',
regexp_instr('ERROR 0x1F at line 402', '0x[0-9A-F]+'), 4) AS error_code,
-- 布尔判断:模式在串内任意位置命中即为真
regexp_like('AB-1234', '[A-Z]{2}-\d{4}') AS code_ok,
regexp_like('AB_1234', '[A-Z]{2}-\d{4}') AS underscore_fails;
-- 计数从指定位置开始:start 之后的命中才计入
SELECT regexp_count('2026-01-15, 2026-02-03, 2026-03-09', '\d{4}', 12) AS late_hits;
-- 按行应用:审计日志里哪些行缺合规编号
WITH audit AS (
SELECT * FROM (VALUES
('AB-1234 ok'),
('missing here'),
('CD-99 ok')
) AS t(line)
)
SELECT
line,
regexp_like(line, '[A-Z]{2}-\d{4}') AS has_code,
regexp_count(line, '\d+') AS digit_runs
FROM audit;How the snippet works
The file runs SELECT statements, touching audit.
The SQL constructs in play: a CTE (WITH … AS) that names an intermediate result before the main query.
Applying it
The audit table is the working surface here.
Statements that matter
WITH audit AS (
SELECT * FROM (VALUES
('AB-1234 ok'),
('missing here'),
('CD-99 ok')
) AS t(line)
)
SELECT
line,
regexp_like(line, '[A-Z]{2}-\d{4}') AS has_code,
regexp_count(line, '\d+') AS digit_runs
FROM audit;
SELECT regexp_count('2026-01-15, 2026-02-03, 2026-03-09', '\d{4}', 12) AS late_hits;
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 relations does the SQL touch?
- `audit`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.