Regular Expressions (Regex) Explained

What is Regex?

Regex (short for Regular Expression) is a sequence of characters that defines a search pattern. It is commonly used for searching, replacing, and validating text.

Why Use Regex?

Basic Regex Syntax

1. Literal Characters

Regular characters match themselves:

hello matches "hello" in a text.

2. Metacharacters (Special Characters)

3. Character Classes (Character Sets)

4. Predefined Character Classes

5. Grouping and Capturing

6. Alternation (OR Operator)

cat|dog → Matches "cat" OR "dog".

7. Lookarounds (Advanced)

Examples

1. Match an Email Address

[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}

2. Match a Phone Number (XXX-XXX-XXXX)

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

3. Match a Date (DD/MM/YYYY or DD-MM-YYYY)

\d{2}[/-]\d{2}[/-]\d{4}

Testing Regex

You can test regex patterns using: