Skip to main content
Development Tools 2025-12-08 Muhammed Ajmal U K 7 min read

Regular Expressions (Regex) Complete Guide: Patterns, Examples & Best Practices

Regular Expressions (Regex) Complete Guide: Patterns, Examples & Best Practices
Quick Take / Key Takeaway
Learn regex syntax, common validation patterns, and practical examples for Python and JavaScript, with testing tips.

What Are Regular Expressions?

Regular expressions (regex) are pattern-matching tools used to search, validate, and manipulate text. Whether you're validating email addresses, extracting phone numbers, or parsing log files, regex is a useful skill for many developers.

This guide covers the basics through more advanced patterns, with practical examples you can use right away.

Regex Basics: Your First Patterns

Literal Matching

The simplest regex matches exact text:

import re

text = "The cat sat on the mat"
pattern = r"cat"
match = re.search(pattern, text)
# Matches: "cat"

Special Characters (Metacharacters)

Character Meaning Example
. Any character (except newline) c.t matches "cat", "cot", "c9t"
^ Start of string ^Hello matches "Hello world"
$ End of string end$ matches "The end"
* 0 or more repetitions ab*c matches "ac", "abc", "abbc"
+ 1 or more repetitions ab+c matches "abc", "abbc"
? 0 or 1 repetition (optional) colou?r matches "color", "colour"
{n} Exactly n repetitions \d{3} matches "123"
{n,m} Between n and m repetitions \d{2,4} matches "12", "123", "1234"

Character Classes and Shortcuts

Predefined Character Classes

Class Matches Equivalent
\d Any digit [0-9]
\D Any non-digit [^0-9]
\w Word character (letter, digit, underscore) [a-zA-Z0-9_]
\W Non-word character [^a-zA-Z0-9_]
\s Whitespace (space, tab, newline) [ \t\n\r\f\v]
\S Non-whitespace [^ \t\n\r\f\v]

Custom Character Classes

# Match vowels
pattern = r"[aeiou]"

# Match consonants (lowercase)
pattern = r"[b-df-hj-np-tv-z]"

# Match digits 1-5
pattern = r"[1-5]"

# Negation: Match anything EXCEPT digits
pattern = r"[^0-9]"

20+ Common Regex Patterns

1. Email Validation

import re

# Basic email pattern
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

emails = ["user@example.com", "invalid.email", "test@domain.co.uk"]
for email in emails:
    if re.match(email_pattern, email):
        print(f"✓ {email} is valid")
    else:
        print(f"✗ {email} is invalid")

2. Phone Number Validation (US)

# Matches: (123) 456-7890, 123-456-7890, 1234567890
phone_pattern = r'^\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})$'

phone = "(555) 123-4567"
match = re.match(phone_pattern, phone)
if match:
    area_code, prefix, number = match.groups()
    print(f"Area: {area_code}, Prefix: {prefix}, Number: {number}")

3. URL Validation

# Matches http://, https://, and www URLs
url_pattern = r'https?://(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&/=]*)'

url = "https://www.example.com/path?query=value"
if re.match(url_pattern, url):
    print("Valid URL")

4. Username Validation

# 3-16 characters, letters, numbers, underscores, hyphens
username_pattern = r'^[a-zA-Z0-9_-]{3,16}$'

usernames = ["john_doe", "user123", "ab", "valid-user"]
for username in usernames:
    valid = bool(re.match(username_pattern, username))
    print(f"{username}: {'✓' if valid else '✗'}")

5. Strong Password Validation

# At least 8 chars, 1 uppercase, 1 lowercase, 1 digit, 1 special char
password_pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$'

password = "SecureP@ss1"
if re.match(password_pattern, password):
    print("Strong password ✓")

6. Date Formats

# YYYY-MM-DD format
date_pattern = r'^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$'

# MM/DD/YYYY format
us_date_pattern = r'^(0[1-9]|1[0-2])/(0[1-9]|[12]\d|3[01])/\d{4}$'

dates = ["2025-01-15", "12/31/2025", "2025-13-01"]
for date in dates:
    valid = bool(re.match(date_pattern, date))
    print(f"{date}: {'✓' if valid else '✗'}")

7. Credit Card Numbers

# Visa, MasterCard, Amex formats
card_patterns = {
    'Visa': r'^4\d{3}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}$',
    'MasterCard': r'^5[1-5]\d{2}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}$',
    'Amex': r'^3[47]\d{2}[-\s]?\d{6}[-\s]?\d{5}$'
}

card = "4532-1234-5678-9010"
for card_type, pattern in card_patterns.items():
    if re.match(pattern, card):
        print(f"Detected {card_type}")

8. IP Address Validation

# IPv4 address
ip_pattern = r'^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$'

ips = ["192.168.1.1", "256.1.1.1", "10.0.0.1"]
for ip in ips:
    valid = bool(re.match(ip_pattern, ip))
    print(f"{ip}: {'✓ Valid' if valid else '✗ Invalid'}")

9. Hex Color Codes

# Matches #FFF or #FFFFFF
hex_color_pattern = r'^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$'

colors = ["#FF5733", "#FFF", "FF5733", "#GGGGGG"]
for color in colors:
    valid = bool(re.match(hex_color_pattern, color))
    print(f"{color}: {'✓' if valid else '✗'}")

10. Extract All Numbers from Text

text = "There are 42 apples and 17 oranges, costing $5.99 total."
numbers = re.findall(r'\d+\.?\d*', text)
print(numbers)  # ['42', '17', '5.99']

Groups and Captures

Capturing Groups

# Extract parts of a date
pattern = r'(\d{4})-(\d{2})-(\d{2})'
date = "2025-01-15"
match = re.match(pattern, date)

if match:
    year, month, day = match.groups()
    print(f"Year: {year}, Month: {month}, Day: {day}")

Named Groups

# More readable with named groups
pattern = r'(?P\d{4})-(?P\d{2})-(?P\d{2})'
match = re.match(pattern, "2025-01-15")

if match:
    print(f"Year: {match.group('year')}")
    print(f"Month: {match.group('month')}")
    print(f"Day: {match.group('day')}")

Non-Capturing Groups

# Use (?:...) when you don't need to capture
pattern = r'(?:https?://)?(?:www\.)?example\.com'
# Groups for alternation, but not captured

Lookahead and Lookbehind

Positive Lookahead (?=...)

# Match "foo" only if followed by "bar"
pattern = r'foo(?=bar)'
text = "foobar foobaz"
matches = re.findall(pattern, text)
print(matches)  # ['foo'] (from 'foobar' only)

Negative Lookahead (?!...)

# Match "foo" NOT followed by "bar"
pattern = r'foo(?!bar)'
text = "foobar foobaz"
matches = re.findall(pattern, text)
print(matches)  # ['foo'] (from 'foobaz' only)

Positive Lookbehind (?<=...)

# Match numbers preceded by "$"
pattern = r'(?<=\$)\d+\.?\d*'
text = "Price: $19.99 and $5"
prices = re.findall(pattern, text)
print(prices)  # ['19.99', '5']

More Practical Examples

11. Extract Hashtags from Text

text = "Learning #Python and #Regex is fun! #100DaysOfCode"
hashtags = re.findall(r'#\w+', text)
print(hashtags)  # ['#Python', '#Regex', '#100DaysOfCode']

12. Remove HTML Tags

html = "<p>This is <b>bold</b> text</p>"
clean_text = re.sub(r'<[^>]+>', '', html)
print(clean_text)  # "This is bold text"

13. Validate ISBN Numbers

# ISBN-10 or ISBN-13
isbn_pattern = r'^(?:\d{9}X|\d{10}|\d{13})$'

isbns = ["0123456789", "123456789X", "9781234567890"]
for isbn in isbns:
    valid = bool(re.match(isbn_pattern, isbn))
    print(f"{isbn}: {'✓' if valid else '✗'}")

14. Extract Email Addresses from Text

text = "Contact us at support@example.com or sales@company.org"
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)
print(emails)  # ['support@example.com', 'sales@company.org']

15. Split on Multiple Delimiters

# Split on comma, semicolon, or pipe
text = "apple,banana;orange|grape"
items = re.split(r'[,;|]', text)
print(items)  # ['apple', 'banana', 'orange', 'grape']

Performance Considerations

Compile Patterns for Repeated Use

# ❌ Slow: Recompiles pattern each time
for text in large_list:
    if re.match(r'\d+', text):
        process(text)

# ✅ Fast: Compile once, use many times
pattern = re.compile(r'\d+')
for text in large_list:
    if pattern.match(text):
        process(text)

Avoid Catastrophic Backtracking

# ❌ Dangerous: Can cause exponential time complexity
bad_pattern = r'(a+)+$'

# ✅ Better: Be specific with quantifiers
good_pattern = r'a+$'

Testing and Debugging Regex

Online Regex Testers

  • ToolPix Regex Tester – Test patterns in real-time with highlighting
  • Regex101.com – Detailed explanation of pattern components
  • RegExr.com – Visual regex builder with cheat sheet

Debugging Tips

  1. Build incrementally – Start simple, add complexity gradually
  2. Test edge cases – Empty strings, special characters, unicode
  3. Use raw strings – Always use r'' in Python to avoid backslash issues
  4. Visualize – Use online tools to see how your pattern matches

Language-Specific Differences

Python (re module)

import re

# Case-insensitive matching
pattern = re.compile(r'hello', re.IGNORECASE)

# Multiline mode
pattern = re.compile(r'^start', re.MULTILINE)

# Verbose mode (allows comments)
pattern = re.compile(r'''
    \d{3}    # Area code
    [-.]     # Separator
    \d{3}    # Prefix
    [-.]     # Separator
    \d{4}    # Number
''', re.VERBOSE)

JavaScript

// Global flag finds all matches
const pattern = /\d+/g;
const text = "123 and 456";
const matches = text.match(pattern);
// ['123', '456']

// Case-insensitive and multiline
const pattern2 = /^hello/im;

Regex Quick Reference Cheat Sheet

Pattern Description
^abc Starts with "abc"
abc$ Ends with "abc"
a|b Match "a" or "b"
\b Word boundary
(?i) Case-insensitive
(?m) Multiline mode
(?s) Dot matches newline

Frequently Asked Questions

Q: What's the difference between * and + in regex?

A: * matches 0 or more occurrences (can match empty string), while + requires at least 1 occurrence. For example, a* matches "", "a", "aa", but a+ only matches "a", "aa" (not empty string).

Q: How do I match a literal dot (.) in regex?

A: Escape it with a backslash: \.. Without the backslash, . matches any character. Example: example\.com matches "example.com" but not "exampleXcom".

Q: What's the best way to learn regex?

A: Practice with real examples using our Regex Tester. Start with simple patterns and gradually add complexity. Try to solve actual problems like validating user input or parsing log files.

Q: Are regex patterns case-sensitive?

A: By default, yes. To make them case-insensitive, use the i flag in JavaScript or re.IGNORECASE in Python. Example: re.match(r'hello', 'HELLO', re.IGNORECASE) matches.

Q: Can regex validate email addresses perfectly?

A: No regex can perfectly validate all valid email addresses due to RFC complexity. Use regex for basic filtering, then verify with an actual email confirmation for production systems.

Q: What is greedy vs lazy matching?

A: Greedy quantifiers (*, +) match as much as possible. Lazy quantifiers (*?, +?) match as little as possible. Example: <.+> in "<b>text</b>" matches the whole string, but <.+?> matches just "<b>" and "</b>" separately.

Conclusion

Regular expressions are useful for text processing, validation, and data extraction. While the syntax can seem cryptic at first, learning the common patterns and fundamentals makes regex much easier to work with.

Key takeaways:

  • Start with simple patterns and build complexity gradually
  • Use character classes and quantifiers for flexible matching
  • Leverage capturing groups to extract specific data
  • Test patterns thoroughly with edge cases
  • Compile patterns for better performance in loops
  • Use online testers to visualize and debug patterns

Ready to test your regex patterns? Try our Regex Tester Tool for instant pattern validation and matching.

Related Tools & Resources:

Ajmal U K - Founder of ToolPix

Muhammed Ajmal U K

Founder & Product Builder • UTHAKKAN

MCA Student and full-stack developer engineering privacy-first browser tools, client-side WASM compilers, and AI web experiences.

Share this article

© 2026 ToolPix by UTHAKKAN. All rights reserved.

Secure Fast Made with in India Launched on StartupBase Featured on StartupBase