🧬 Regex for Advanced Filtering

Last Updated: January 2026


Regex allows pattern-based filtering when simple conditions are not enough. It is commonly used with:

  • REGEXP / RLIKE (MySQL)
  • ~ operator (PostgreSQL)

Hinglish Tip 🗣: Regex tab use hota hai jab filter rule-based pattern par depend karta ho.


Basic Usage

SELECT column_name
FROM table_name
WHERE column_name REGEXP 'pattern';

🔤 Core Regex Symbols

SymbolDescriptionExampleMatches
^Matches the start of the string or line^Hello

Hello there (start match)

$Matches the end of the string or lineend$

The end (end match)

{m}

Matches exactly m repetitions of the preceding element

a{3}aaa
{m,}

Matches at least m repetitions of the preceding element

a{2,}

aa, aaa

{(m, n)}

Matches between m and n repetitions

a{(2, 4)}

aa, aaa, aaaa

( ... )Groups patterns or captures matched substring(ab)+

ab, abab, ababab

|OR operator: matches either pattern on left or rightcat|dog

cat or dog

[abc]Character class: matches any one character listed[aeiou]any vowel
[^abc]

Negated character class: matches any character not listed

[^0-9]any non-digit character
\Escape character: matches a literal backslash or special char\.

a literal dot .

.Matches any single character except newlinea.b

aab, acb, a9b

*Matches zero or more repetitions of the previous characterca*t

ct, cat, caaaat

+Matches one or more repetitions of the previous charactergo+gle

gogle, google, gooogle

?Matches zero or one repetition (makes preceding optional)colou?r

color, colour

\bMatches a word boundary\bcat\b

cat but not cats or cat.

\dMatches any digit (0-9)\d{}

123, 456, 007

\DMatches any non-digit character\D+

abc, !@#

\wMatches any alphanumeric character or underscore\w+

hello123, _var

\WMatches any non-word character\W+

!@#, spaces

\sMatches any whitespace character (space, tab, newline)\s+space, tab, newline
\SMatches any non-whitespace character\S+

hello, 123


🔍 SQL Examples

^ — Starts With

SELECT name
FROM students
WHERE name REGEXP '^A';

$ — Ends With

SELECT name
FROM students
WHERE name REGEXP 'n$';

| — OR

SELECT name
FROM students
WHERE name REGEXP 'Ram|Shyam';

. — Any One Character

SELECT code
FROM products
WHERE code REGEXP 'A.B';

Matches: A1B, ACB, A-B


* — Zero or More

SELECT value
FROM logs
WHERE value REGEXP 'ab*';

Matches: a, ab, abb


[] — Character Set

SELECT name
FROM students
WHERE name REGEXP '^[A-Z]';

+ — One or More

SELECT name
FROM users
WHERE name REGEXP 'a+';

? — Zero or One

SELECT color
FROM items
WHERE color REGEXP 'colou?r';

Matches: color, colour


{m} — Exact Count

SELECT pin
FROM addresses
WHERE pin REGEXP '^[0-9]{6}$';

{m, or } — Minimum Count

SELECT username
FROM users
WHERE username REGEXP '[a-z]{5,}';

{n, m} — Range Count

SELECT code
FROM products
WHERE code REGEXP '[A-Z]{2,4}';

⚠️ Important Notes

  • Regex support varies slightly by database
  • Always test patterns before using in production
  • Use anchors (^, $) to avoid partial matches