Python Regular Expressions

A Regular Expression (Regex) is a sequence of characters used to search, match, and manipulate text patterns. Python provides the built-in re module for working with regular expressions. Importing the re Module Example search() The search() function searches for a pattern anywhere in a string. Syntax Example Output: match() The match() function checks for a […]

2 mins read Lesson 42 of 56 75% through track

A Regular Expression (Regex) is a sequence of characters used to search, match, and manipulate text patterns. Python provides the built-in re module for working with regular expressions.

Importing the re Module

Example

import re

The search() function searches for a pattern anywhere in a string.

Syntax

re.search(pattern, string)

Example

import re

text = "Welcome to Python"

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

print(result)

Output:

<re.Match object>

match()

The match() function checks for a match only at the beginning of a string.

Example

import re

text = "Python Programming"

result = re.match("Python", text)

print(result)

Output:

<re.Match object>

findall()

The findall() function returns all matches as a list.

Example

import re

text = "Python is easy. Python is powerful."

result = re.findall("Python", text)

print(result)

Output:

['Python', 'Python']

split()

The split() function splits a string where the pattern matches.

Example

import re

text = "apple,banana,mango"

result = re.split(",", text)

print(result)

Output:

['apple', 'banana', 'mango']

sub()

The sub() function replaces matches with another value.

Example

import re

text = "I like Java"

result = re.sub("Java", "Python", text)

print(result)

Output:

I like Python

Common Regex Patterns

PatternDescription
.Any character except newline
^Starts with
$Ends with
*Zero or more occurrences
+One or more occurrences
?Zero or one occurrence
\dAny digit (0-9)
\DAny non-digit
\wAny word character
\WAny non-word character
\sAny whitespace character

Find All Digits

Example

import re

text = "My age is 25"

result = re.findall(r"\d", text)

print(result)

Output:

['2', '5']

Validate Email Pattern

Example

import re

email = "user@example.com"

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

if re.match(pattern, email):
    print("Valid Email")
else:
    print("Invalid Email")

Output:

Valid Email

Summary

  • Regular Expressions are used for pattern matching.
  • Python provides the re module for regex operations.
  • search() finds a pattern anywhere in a string.
  • match() checks only at the beginning of a string.
  • findall() returns all matching values.
  • split() splits a string based on a pattern.
  • sub() replaces matched text.
  • Regex is commonly used for validation, searching, and text processing.