SQL · Module 5 · Lesson 61 min read

Pattern Matching & Regular Expressions

Regex operators (PostgreSQL)

OperatorMeaning
~matches (case-sensitive)
~*matches (case-insensitive)
!~does not match
!~*does not match (case-insensitive)

Quick regex refresher

  • ^ start, $ end
  • . any character, \d digit, \w word character, \s whitespace
  • [abc] one of, [^abc] none of, [0-9], [A-Za-z]
  • * 0+, + 1+, ? 0 or 1, {10} exactly 10, {2,4} 2 to 4
  • ( ) group, | OR

Regex functions

  • regexp_replace(s, pattern, replacement, flags) – use the 'g' flag to replace all matches
  • regexp_match(s, pattern) → the first match (as an array of groups)
  • regexp_matches(s, pattern, 'g') → all matches (one row each)
  • regexp_split_to_array(s, pattern) / regexp_split_to_table
  • regexp_count(s, pattern), regexp_like(s, pattern) (PostgreSQL 15+)
  • substring(s FROM pattern) – the first match (or first group)

Common uses

  • Validation in CHECK constraints: CHECK (phone ~ '^9[78]\d{8}$')
  • Cleaning: remove non-digits regexp_replace(phone, '\D', '', 'g'), collapse spaces regexp_replace(s, '\s+', ' ', 'g')
  • Extracting: numbers from text, hashtags, domains

SIMILAR TO

A mix of LIKE and regex from the SQL standard. It's rarely used — prefer ~.

Performance

Regex filters scan every row. For searching large tables, use a trigram index (pg_trgm) or full-text search (Unit 13).

⚠️ In standard-conforming strings, a backslash is just a normal character, so '\d' works as written.

Example

SQL
-- Titles that start with a capital letter followed by lowercase letters only
SELECT DISTINCT title FROM expenses WHERE title ~ '^[A-Z][a-z]+$';
-- Concert, Dinner, Fuel, Groceries, Jacket, Paragliding, Vegetables

-- Case-insensitive regex: titles mentioning bill OR fuel
SELECT title FROM expenses WHERE title ~* '(bill|fuel)';

-- Validate Nepali mobile numbers with a CHECK constraint
CREATE TABLE phone_book (
  name  TEXT NOT NULL,
  phone TEXT NOT NULL CHECK (phone ~ '^9[78]\d{8}$')
);
INSERT INTO phone_book VALUES ('Asha', '9801234567');        -- ✅
-- INSERT INTO phone_book VALUES ('Bad', '12345');           -- ❌ violates check constraint

-- Clean messy phone numbers: keep digits only
SELECT raw, regexp_replace(raw, '\D', '', 'g') AS digits
FROM (VALUES ('+977 980-123-4567'), ('(98) 1234 5678')) t(raw);
-- 9779801234567 | 9812345678

-- Collapse extra spaces
SELECT regexp_replace('Weekly    groceries   at  Bhatbhateni', '\s+', ' ', 'g') AS tidy;

-- Extract the amount from a bank SMS
SELECT (regexp_match(sms, 'Rs\.?\s?([\d,]+(\.\d+)?)'))[1] AS amount_text,
       replace((regexp_match(sms, 'Rs\.?\s?([\d,]+(\.\d+)?)'))[1], ',', '')::numeric AS amount
FROM (VALUES ('Your a/c debited by Rs. 1,250.00 at Daraz on 24-11-2026')) t(sms);
-- 1,250.00 | 1250.00

-- Find every hashtag in a note
SELECT m[1] AS tag
FROM regexp_matches('Trip to #Pokhara with #friends #holiday', '#(\w+)', 'g') AS m;
-- Pokhara, friends, holiday

DROP TABLE phone_book;