Related Articles

Related Articles

How to validate MAC address using Regular Expression
  • Last Updated : 19 Oct, 2020

Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression.

A valid MAC address must satisfy the following conditions: 
 

  1. It must contain 12 hexadecimal digits.
  2. One way to represent them is to form six pairs of the characters separated with a hyphen (-) or colon(:). For example, 01-23-45-67-89-AB is a valid MAC address.
  3. Another way to represent them is to form three groups of four hexadecimal digits separated by dots(.). For example, 0123.4567.89AB is a valid MAC address.

Examples: 

Input: str = “01-23-45-67-89-AB”; 
Output: true 
Explanation: 
The given string satisfies all the above mentioned conditions. Therefore, it is a valid MAC address.
Input: str = “01-23-45-67-89-AH”; 
Output: false 
Explanation: 
The given string contains ‘H’, the valid hexadecimal digits should be followed by letter from a-f, A-F, and 0-9. Therefore, it is not a valid MAC address.
Input: str = “01-23-45-67-AH”; 
Output: false 
Explanation: 
The given string has five groups of two hexadecimal digits. Therefore, it is not a valid MAC address. 
 

Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer. 



  • Get the String.
  • Create a regular expression to check valid MAC address as mentioned below: 

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})$”; 

  • Where: 
    • ^ represents the starting of the string.
    • ([0-9A-Fa-f]{2}[:-]){5} represents the five groups of two hexadecimal digits separated by hyphens (-) or colons (:)
    • ([0-9A-Fa-f]{2}) represents the one groups of two hexadecimal digits.
    • | represents the or.
    • ( represents the starting of the group.
    • [0-9a-fA-F]{4}\\. represents the first part of four hexadecimal digits separated by dots (.).
    • [0-9a-fA-F]{4}\\. represents the second part of four hexadecimal digits separated by dots (.).
    • [0-9a-fA-F]{4} represents the third part of four hexadecimal digits.
    • ) represents the ending of the group.
    • $ represents the ending of the string.
  • Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher().
  • Return true if the string matches with the given regular expression, else return false.

Below is the implementation of the above approach:
 

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to validate
// MAC address using
// regular expression
 
import java.util.regex.*;
class GFG {
 
    // Function to validate
    // MAC address
    // using regular expression
    public static boolean
    isValidMACAddress(String str)
    {
        // Regex to check valid
        // MAC address
        String 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})$";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the string is empty
        // return false
        if (str == null) {
            return false;
        }
 
        // Find match between given string
        // and regular expression
        // uSing Pattern.matcher()
 
        Matcher m = p.matcher(str);
 
        // Return if the string
        // matched the ReGex
        return m.matches();
    }
 
    // Driver code
    public static void main(String args[])
    {
 
        // Test Case 1:
        String str2 = "01-23-45-67-89-AB";
        System.out.println(
            isValidMACAddress(str2));
 
        // Test Case 2:
        String str3 = "01:23:45:67:89:AB";
        System.out.println(
            isValidMACAddress(str3));
 
        // Test Case 3:
        String str1 = "0123.4567.89AB";
        System.out.println(
            isValidMACAddress(str1));
 
        // Test Case 4:
        String str4 = "01-23-45-67-89-AH";
        System.out.println(
            isValidMACAddress(str4));
 
        // Test Case 5:
        String str5 = "01-23-45-67-AH";
        System.out.println(
            isValidMACAddress(str5));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to validate
# MAC address using
# using regular expression
import re
 
# Function to validate MAC address.
def isValidMACAddress(str):
 
    # Regex to check valid
    # MAC address 
    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})$")
     
    # Compile the ReGex
    p = re.compile(regex)
 
    # If the string is empty
    # return false
    if (str == None):
        return False
 
    # Return if the string
    # matched the ReGex
    if(re.search(p, str)):
        return True
    else:
        return False
 
# Driver code
 
# Test Case 1:
str1 = "01-23-45-67-89-AB"
print(isValidMACAddress(str1))
 
# Test Case 2:
str2 = "01:23:45:67:89:AB"
print(isValidMACAddress(str2))
 
# Test Case 3:
str3 = "0123.4567.89AB"
print(isValidMACAddress(str3))
 
# Test Case 4:
str4 = "01-23-45-67-89-AH"
print(isValidMACAddress(str4))
 
# Test Case 5:
str5 = "01-23-45-67-AH"
print(isValidMACAddress(str5))
 
# This code is contributed by avanitrachhadiya2155

chevron_right


Output: 

true
true
true
false
false

 

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :