Mastering Regular Expressions: Essential Patterns and Practical Examples

Discover the power of regular expressions with our guide. Learn essential patterns for email and phone number validation, and explore practical examples for effective text manipulation in various applications.



Practical Examples of Regular Expressions

Email Validation

Syntax

\w+@\w+\.\w+

This regex matches a basic email format, consisting of a word character sequence followed by an '@' symbol, another word character sequence, and a dot followed by one or more word characters.

Phone Number Validation

Syntax

\d{3}-\d{3}-\d{4}

This regex matches a phone number in the format ###-###-####.

Extracting Dates

Syntax

\d{4}-\d{2}-\d{2}

This regex extracts dates in the format YYYY-MM-DD.

Finding URLs

Syntax

http(s)?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+

This regex matches URLs, including http or https protocols.

Removing HTML Tags

Syntax

<.*?>

This regex matches any HTML tag, allowing for removal of tags from a text.

Password Validation

Syntax

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$

This regex enforces a strong password policy, requiring at least one lowercase letter, one uppercase letter, one number, and one special character, with a minimum length of 8 characters.

Extracting Numbers from Text

Syntax

\d+

This regex extracts all numbers from a given text.

Finding Specific Words

Syntax

\bword\b

This regex finds the exact word "word" within a text, ensuring it's a complete word.

Matching IP Addresses

Syntax

\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b

This regex matches a valid IPv4 address.

Replacing Text

Syntax

text.replace(/old_text/g, 'new_text')

This replaces all occurrences of "old_text" with "new_text" in the string "text".

Extracting Text Between Tags

Syntax

(.*?)<\/div>

This regex extracts text between

and
tags.

Finding Duplicate Words

Syntax

\b(\w+)\s+\1\b

This regex finds duplicate words within a text.

Extracting File Names

Syntax

[^/\\]+$

This regex extracts the file name from a file path.

Validating Credit Card Numbers

Syntax

^(?:4[0-9]{12}(?:[0-9]{3})?|[25][1-9]{14}|[6][013][0-9]{12}|3[47][0-9]{13})$

This regex validates a credit card number based on common card types.

Extracting Social Security Numbers

Syntax

\d{3}-\d{2}-\d{4}

This regex extracts a social security number in the format ###-##-####.

Note: These examples provide a basic overview. You might need to modify the regex patterns based on specific requirements and variations in data formats.