Code for How to Use Regular Expressions in Python Tutorial


View on Github

match.py

import re # stands for regular expression 
# a regular expression for validating a password
match_regex = r"^(?=.*[0-9]).{8,}$"
# a list of example passwords
passwords = ["pwd", "password", "password1"]
for pwd in passwords:
    m = re.match(match_regex, pwd)
    print(f"Password: {pwd}, validate password strength: {bool(m)}")

search.py

import re

# part of ipconfig output
example_text = """
Wireless LAN adapter Wi-Fi:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::380e:9710:5172:caee%2
   IPv4 Address. . . . . . . . . . . : 192.168.1.100
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.1
"""

# regex for IPv4 address
ip_address_regex = r"((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\.(?!$)|$)){4}"
# use re.search() method to get the match object
match = re.search(ip_address_regex, example_text)
print(match)

finditer.py

import re

# fake ipconfig output
example_text = """
Ethernet adapter Ethernet:

   Media State . . . . . . . . . . . : Media disconnected
   Physical Address. . . . . . . . . : 88-90-E6-28-35-FA

Ethernet adapter Ethernet 2:

   Physical Address. . . . . . . . . : 04-00-4C-4F-4F-60
   Autoconfiguration IPv4 Address. . : 169.254.204.56(Preferred)

Wireless LAN adapter Local Area Connection* 2:

   Media State . . . . . . . . . . . : Media disconnected
   Physical Address. . . . . . . . . : B8-21-5E-D3-66-98

Wireless LAN adapter Wi-Fi:

   Physical Address. . . . . . . . . : A0-00-79-AA-62-74
   IPv4 Address. . . . . . . . . . . : 192.168.1.101(Preferred)
   Default Gateway . . . . . . . . . : 192.168.1.1
"""
# regex for MAC address
mac_address_regex = r"([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})"
# iterate over matches and extract MAC addresses
extracted_mac_addresses = [ m.group(0) for m in re.finditer(mac_address_regex, example_text) ]
print(extracted_mac_addresses)

sub.py

import re

# a basic regular expression for email matching
email_regex = r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+"
# example text to test with
example_text = """
Subject: This is a text email!
From: John Doe <john@doe.com>
Some text here!
"""
# substitute any email found with [email protected]
print(re.sub(email_regex, "[email protected]", example_text))