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