Member-only story
Functional programming (FP) emphasizes immutability, stateless functions, and declarative code. When combined with regular expressions (regex), Python developers gain powerful abstraction layers that promote cleaner APIs, simpler debugging, and less boilerplate code.
In this article, we’ll discuss three ways to combine regex and FP in Python to solve common text-processing challenges.
Map and Compose High-Order Functions
High-order functions take other functions as arguments or return functions as their output. By composing higher-order functions like map()
, filter()
, and reduce()
with regex, we can transform texts elegantly and concisely.
Let’s say we want to extract email addresses from a list of strings:
import re
emails_regex = re.compile(r"\S+@\S+")def extract_emails(text: str) -> list[str]:
return emails_regex.findall(text)
texts = [
"Contact john@example.com for sales.",
"Send questions to info@example.com.",
"Visit www.example.com for more info.",
]
emails = list(map(extract_emails, texts))
print(emails)