How to validate MAC address using Regular Expression
Last Updated :
22 Dec, 2022
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:
- It must contain 12 hexadecimal digits.
- 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.
- 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:
C++
// C++ program to validate the
// MAC address
// using Regular Expression
#include <iostream>
#include <regex>
using namespace std;
// Function to validate the MAC address
bool isValidMACAddress(string str)
{
// Regex to check valid MAC address
const regex pattern(
"^([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})$");
// If the MAC address
// is empty return false
if (str.empty())
{
return false;
}
// Return true if the MAC address
// matched the ReGex
if (regex_match(str, pattern))
{
return true;
}
else
{
return false;
}
}
// Driver Code
int main()
{
// Test Case 1:
string str1 = "01-23-45-67-89-AB";
cout << isValidMACAddress(str1) << endl;
// Test Case 2:
string str2 = "01:23:45:67:89:AB";
cout << isValidMACAddress(str2) << endl;
// Test Case 3:
string str3 = "0123.4567.89AB";
cout << isValidMACAddress(str3) << endl;
// Test Case 4:
string str4 = "01-23-45-67-89-AH";
cout << isValidMACAddress(str4) << endl;
// Test Case 5:
string str5 = "01-23-45-67-AH";
cout << isValidMACAddress(str5) << endl;
return 0;
}
// This code is contributed by yuvraj_chandra
Java
// 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 str1 = "01-23-45-67-89-AB";
System.out.println(isValidMACAddress(str1));
// Test Case 2:
String str2 = "01:23:45:67:89:AB";
System.out.println(isValidMACAddress(str2));
// Test Case 3:
String str3 = "0123.4567.89AB";
System.out.println(isValidMACAddress(str3));
// 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));
}
}
Python3
# 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
C#
// C# program to validate
// MAC address using
// regular expression
using System;
using System.Text.RegularExpressions;
class GFG {
// Function to validate
// MAC address
// using regular expression
public static bool 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
Regex p = new Regex(regex);
// If the string is empty
// return false
if (str == null)
{
return false;
}
// Find match between given string
// and regular expression
// uSing Pattern.matcher()
Match m = p.Match(str);
// Return if the string
// matched the ReGex
return m.Success;
}
// Driver code
public static void Main()
{
// Test Case 1:
string str1 = "01-23-45-67-89-AB";
Console.WriteLine(isValidMACAddress(str1));
// Test Case 2:
string str2 = "01:23:45:67:89:AB";
Console.WriteLine(isValidMACAddress(str2));
// Test Case 3:
string str3 = "0123.4567.89AB";
Console.WriteLine(isValidMACAddress(str3));
// Test Case 4:
string str4 = "01-23-45-67-89-AH";
Console.WriteLine(isValidMACAddress(str4));
// Test Case 5:
string str5 = "01-23-45-67-AH";
Console.WriteLine(isValidMACAddress(str5));
}
}
// This code is contributed by Aman Kumar.
JavaScript
// Javascript program to validate
// MAC Address using Regular Expression
// Function to validate the
// MAC_Address
function isValidMACAddress(str) {
// Regex to check valid
// MAC_Address
let regex = new RegExp(/^([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})$/);
// if str
// is empty return false
if (str == null) {
return "false";
}
// Return true if the str
// matched the ReGex
if (regex.test(str) == true) {
return "true";
}
else {
return "false";
}
}
// Driver Code
// Test Case 1:
let str1 = "01-23-45-67-89-AB";
console.log(isValidMACAddress(str1));
// Test Case 2:
let str2 = "01:23:45:67:89:AB";
console.log(isValidMACAddress(str2));
// Test Case 3:
let str3 = "0123.4567.89AB";
console.log(isValidMACAddress(str3));
// Test Case 4:
let str4 = "01-23-45-67-89-AH";
console.log(isValidMACAddress(str4));
// Test Case 5:
let str5 = "01-23-45-67-AH";
console.log(isValidMACAddress(str5));
// This code is contributed by Rahul Chauhan
Outputtrue
true
true
false
false
Time Complexity: O(N) for each testcase, where N is the length of the given string.
Auxiliary Space: O(1)
Similar Reads
How to Validate MICR Code using Regular Expression? MICR stands for Magnetic Ink Character Recognition. This technology provides transaction security, ensuring the correctness of bank cheques. MICR code makes cheque processing faster and safer. MICR Technology reduces cheque-related fraudulent activities. Structure of a Magnetic Ink Character Recogni
5 min read
How to validate IFSC Code using Regular Expression Given string str, the task is to check whether the given string is a valid IFSC (Indian Financial System) Code or not by using Regular Expression. The valid IFSC (Indian Financial System) Code must satisfy the following conditions: It should be 11 characters long.The first four characters should be
8 min read
How to validate an IP address using Regular Expressions in Java Given an IP address, the task is to validate this IP address with the help of Regular Expressions.The IP address is a string in the form "A.B.C.D", where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can't be greater than 3.Examples: Inpu
3 min read
How to validate PAN Card number using Regular Expression Given string str of alphanumeric characters, the task is to check whether the string is a valid PAN (Permanent Account Number) Card number or not by using Regular Expression.The valid PAN Card number must satisfy the following conditions: It should be ten characters long.The first five characters sh
6 min read
How to validate a domain name using Regular Expression Given string str, the task is to check whether the given string is a valid domain name or not by using Regular Expression.The valid domain name must satisfy the following conditions: The domain name should be a-z or A-Z or 0-9 and hyphen (-).The domain name should be between 1 and 63 characters long
6 min read
How to validate ISIN using Regular Expressions ISIN stands for International Securities Identification Number. Given string str, the task is to check whether the given string is a valid ISIN(International Securities Identification Number) or not by using Regular Expression. The valid ISIN(International Securities Identification Number) must sati
6 min read
How to validate CVV number using Regular Expression Given string str, the task is to check whether it is a valid CVV (Card Verification Value) number or not by using Regular Expression. The valid CVV (Card Verification Value) number must satisfy the following conditions: It should have 3 or 4 digits.It should have a digit between 0-9.It should not ha
5 min read
How to validate Visa Card number using Regular Expression Given a string str, the task is to check whether the given string is a valid Visa Card number or not by using Regular Expression. The valid Visa Card number must satisfy the following conditions: It should be 13 or 16 digits long, new cards have 16 digits and old cards have 13 digits.It should start
6 min read
How to validate pin code of India using Regular Expression Given a string of positive number ranging from 0 to 9, the task is to check whether the number is valid pin code or not by using a Regular Expression. The valid pin code of India must satisfy the following conditions. It can be only six digits.It should not start with zero.First digit of the pin cod
6 min read