![]() |
VOOZH | about |
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.
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})$";
Below is the implementation of the above approach:
true true true false false
Time Complexity: O(N) for each testcase, where N is the length of the given string.
Auxiliary Space: O(1)