Program to validate MAC address using Regular Expression in Python
In this article, we will learn whether a given string is a valid MAC address using Regular Expression in Python.
Before I go forward, I hope you understand what is a MAC address.
Examples of MAC address:
40-9F-38-EF-2C-85 40:9F:38:EF:2C:85 409F.38EF.2C85
Validate MAC address
1. Import the necessary module(i.e. import re).
2. Get the user input string.
3. Create a regular expression that checks the valid MAC address.
4. Match the string with the regular expression.
5. Finally, return true if strings match, else return false.
import re def is_valid(str): #regural expression regex = ("^([0-9A-Fa-f]{2}[:-])" +"{5}([0-9A-Fa-f]{2})|" +"([0-9a-fA-F]{4}\\." +"[0-9a-fA-F]{4}\\." +"[0-9a-fA-F]{4})$") match = re.compile(regex) if (str == None): return False if(re.search(match, str)): return True else: return False input_string = input("Enter the MAC address: ") if(is_valid(input_string)): print("Given string is valid MAC address") else: print("Given string is a not valid MAC adress")
Output
Enter the MAC address: 40-9F-38-EF-2C-85 Given string is valid MAC address Enter the MAC address: 12-34-56-78-90 Given string is a not valid MAC adress
As you can see, we have performed this task successfully. The user will insert the MAC address and our Python code is checking if it is validated or not.
Also, refer
Leave a Reply