Skip to main content

Re Module

Regular expressions are powerful tools in programming languages for searching, matching, and manipulating text. The re module in Python provides support for regular expressions.


Write a program that accepts a list of email addresses and uses regular expressions to extract the username and domain of each address.

JavaScript implementation

const emailAddresses = [

const regex = /([^@]+)@(.+)/;

emailAddresses.forEach((email) => {
const [_, username, domain] = email.match(regex);
console.log(`Username: ${username}, Domain: ${domain}`);

Python implementation:

import re

email_addresses = [

regex = re.compile(r"([^@]+)@(.+)")

for email in email_addresses:
match = regex.match(email)
if match:
username, domain = match.groups()
print(f"Username: {username}, Domain: {domain}")

In Python, prefixing a string with r indicates a raw string literal, which treats backslashes as literal characters.

Code Highlight

  • In JavaScript, regular expressions can be defined using /.../ or new Regex(...), while in Python, you can create a regular expression using the re.compile() function.

Difference Quick View

Creating a regular expressionconst myReg = /pattern/; or new Regex(pattern)my_regex = re.compile(r'pattern')
Matching a regular expressionmyReg.test(myStr)my_regex.match(my_str)
Finding the first matchmyReg.exec(myStr)
Finding all matchesmyStr.match(myReg)my_regex.findall(my_str)
Replacing matchesmyStr.replace(myReg, replacement)my_regex.sub(replacement, my_str)
Splitting a string using a regular expressionmyStr.split(myReg)my_regex.split(my_str)

In addition to using re.compile() to create a regular expression, you can also directly use methods like and re.split() from the re module to achieve the same functionality, such as:

import re'pattern', my_str)
re.split(r'pattern', my_str)