🧬 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
| Symbol | Description | Example | Matches |
|---|---|---|---|
^ | Matches the start of the string or line | ^Hello |
|
$ | Matches the end of the string or line | end$ |
|
{m} | Matches exactly | a{3} | aaa |
{m,} | Matches at least | a{2,} |
|
{(m, n)} | Matches between | a{(2, 4)} |
|
( ... ) | Groups patterns or captures matched substring | (ab)+ |
|
| | OR operator: matches either pattern on left or right | cat|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 newline | a.b |
|
* | Matches zero or more repetitions of the previous character | ca*t |
|
+ | Matches one or more repetitions of the previous character | go+gle |
|
? | Matches zero or one repetition (makes preceding optional) | colou?r |
|
\b | Matches a word boundary | \bcat\b |
|
\d | Matches any digit (0-9) | \d{} |
|
\D | Matches any non-digit character | \D+ |
|
\w | Matches any alphanumeric character or underscore | \w+ |
|
\W | Matches any non-word character | \W+ |
|
\s | Matches any whitespace character (space, tab, newline) | \s+ | space, tab, newline |
\S | Matches any non-whitespace character | \S+ |
|
🔍 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