[python]regex to find mac address

This is my interface mac address

To search for the substring from the lines of string i use the search method.

This is the pattern pattern = r"([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}"
And in order to return the substring only use the group() method.

# this is an example on how to get the mac address using regex.
from subprocess import check_output
import re

pattern = r"([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}"

def check_interface(interface):
    return (check_output(["ifconfig", interface])).decode('utf-8')

if __name__ == "__main__":
    interface_result = check_interface("eth0")
    print(re.search(pattern, interface_result).group())

If you print the re.search result without using group method you will get the entire regex object information.

Further reading the documentation makes me understand the difference between match and search methods. So I am finding a word which can be anywhere in the multi-line strings i need to use search method, the match only returns if the match is found at the beginning of the string.

Alternate regex pattern can be:

# Alternate short hand way. \d is the same as [0-9]
pattern2 = r"([\da-fA-F]{2}:){5}[\da-fA-F]{2}"

Another method:
pattern3 = r"([0-9aA-fF]{2}:){5}[0-9aA-fF]{2}"

Another method, but this one is bad:

# \w is the same as [0-9aA-zZ]
pattern4 = r"(\w{2}:){5}\w{2}"

This is bad because mac address is hexidecimal so from 0 until f, and f is the max, using the short hand \w it will match things like this 0z:fx:ra:9r:r8 which is bad in the context of mac address.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s