Regex (Regular Expressions)

Python tutorial · PySpark.in

Regular Expressions (Regex)

Regular Expressions (Regex) are powerful tools used for pattern matching and text processing. In Python, regex allows developers to search, validate, extract, and manipulate text efficiently.

Python provides built-in support for regex through the re module.

Regex is widely used in:

Why Use Regex?

Regex helps when you need to:

✔ Check if input matches a pattern
✔ Find specific words in large text
✔ Extract emails, phone numbers, URLs
✔ Replace text automatically

Example use cases:

Python re Module

To use regex in Python:

```

Hide

import re

```

Basic Regex Patterns

Pattern

Meaning

.

Any character

\d

Digit (0–9)

\w

Word character

\s

Whitespace

^

Start of string

$

End of string

*

0 or more

+

1 or more

?

Optional

Important Functions

re.search()

Finds first match in string.

```

import re

text = "Python is powerful"
result = re.search("Python", text)

print(result)

```

re.findall()

Returns all matches.

```

text = "apple banana apple"

print(re.findall("apple", text))

```

re.match()

Matches only at the beginning.

```

X=re.match("Hello", "Hello World")

print(X)

```

re.sub()

Replaces text.

```

text = "I love cats"

print(re.sub("cats", "dogs", text))

```

Practical Examples

Email Validation

```

import re

email = "user@gmail.com"

pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"

print(bool(re.match(pattern, email)))

```

Extract Numbers

```

text = "Marks: 85 and 92"

print(re.findall(r"\d+", text))

```

Website URL Validation

```

url = "https://www.google.com"

pattern = r"^(https?:\/\/)?(www\.)?[a-zA-Z0-9-]+\.[a-zA-Z]{2,}$"

print(bool(re.match(pattern, url)))

```

Advantages of Regex

✔ Saves time in text processing
✔ Handles complex search patterns
✔ Useful in real-world applications
✔ Essential skill for developers

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges