Regex – Regular Expression

Here’s a quick note about regex — it’s a powerful tool that can greatly assist you with searching and replacing text

A Regular Expression (or Regex) is a special sequence of characters used to search, match, and manipulate strings in text.

In programming, when we work with strings — searching, comparing, or replacing — regex gives us a flexible way to define patterns.
Think of regex as a template (mold): any string that fits the mold is considered a match.

Writing regex is like crafting a mold — everything that fits inside it will match.

hybrid-pages

I. Regex Components

Before writing complex patterns, let’s go through the most basic building blocks of regex.

Character Sets

Pattern Meaning
[a-z] Lowercase letters a → z
[A-Z] Uppercase letters A → Z
[0-9] or \d Digits 0 → 9
\t, \n, \s Whitespace (tab, newline, space)
. Any character except newline
^ Start of a line
$ End of a line
A|B Match A or B

Brackets & Quantifiers

Symbol Description (EN)  
() Group – used for sub-patterns
[] Character class
{n} Exactly n times
{n,} At least n times
{m,n} Between m and n times

Repetition Operators

Symbol Equivalent Meaning (EN)  
* {0,} Zero or more
+ {1,} One or more
? {0,1} Optional

Example


ab?   # matches "a" or "ab"
 

II. Advanced Patterns

Negative Lookahead (?!pattern)

Matches only if the pattern does not appear next.


import re
comp = re.compile(r'ab(?!cd)ef')

print(comp.match('abcdefgh'))  # None
print(comp.match('abefgh'))    # abef
 

Non-capturing Group (?:pattern)

Matches the pattern but doesn’t capture it.


import re

comp = re.compile(r'(\d{4})-(?:\d{2})-(\d{2})')
print(comp.findall('1999-06-07'))
# [('1999', '07')]
 

III. Example: Validate IPv4 Address

IPv4 has 4 octets separated by dots, each from 0–255.
Example: 192.168.1.1

 

Step 1: Define One Octet

hybrid-pages


[0-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]

Step 2: Combine Four Octets

Combine them with dots and use anchors ^ and $ to ensure full match


import re

regex = r'^(?:[0-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(?:\.(?:[0-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){3}$'
pattern = re.compile(regex, re.M)

content = """1.2.3.04
169.254.1.1
1.1.1.1
8.8.8.8
300.300.300.300
255.255.255.255
"""

print(pattern.findall(content))

Result


['169.254.1.1', '1.1.1.1';, '8.8.8.8', '255.255.255.255']

IV. Summary

Regex is a powerful pattern tool for developers — it helps validate inputs, extract data, and automate text handling.
Just remember: make it readable, or you’ll hate debugging your own regex later =)))

Next/Previous Post

buymeacoffee
Regex – Regular Expression - codevel.io | Codevel.io