find mac addresses in a string using regex in python

To extract MAC addresses from a string in Python using regular expressions, we can use the re library. Here's an example code snippet that should work for most MAC address formats:

main.py
import re

string_with_macs = "Sample string with MAC addresses: aa:bb:cc:dd:ee:ff and 00-11-22-33-44-55"
mac_addresses = re.findall(r'([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})', string_with_macs)

print(mac_addresses)
217 chars
7 lines

In this code snippet, we first import the re library. We then define a sample string that contains MAC addresses. Using the re.findall() method, we search for patterns that match any sequence of six sets of two hexadecimal digits, separated by colons or hyphens. The resulting mac_addresses variable should contain all matched MAC addresses in the string as a list.

Note that this approach assumes that the MAC addresses in the string are formatted using either colons or hyphens as the delimiter. If the MAC addresses in your string are formatted differently, you may need to adjust the regular expression pattern accordingly.

gistlibby LogSnag