Mac address regex Java

Mac address

Mac address is a unique identifier assigned to network interface controllers like WiFi routers, Ethernet controllers, etc. It has a format of six groups of 2 hexadecimal digits separated by dash or colon (e.g. 00:00:5e:00:53:af). Mac address regular expression can be used to validate that a certain string contains mac address or extract mac address from a given string.

Simple Mac address regex (IEEE 802)

Below is a simple mac address regex that supports dashes or colons as separators:

Pattern.compile("^(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})$")

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Example code in Java:

import java.util.regex.Pattern;
import java.util.regex.MatchResult;
import java.util.Arrays;

public class Main {

    public static void main(String []args) {
        // Validate mac address
        boolean isMatch = Pattern.compile("^(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})$")
               .matcher("00:00:5e:00:53:af")
               .find(); 
        System.out.println(isMatch); // prints true
        
        // Extract mac address from a string
        String[] matches = Pattern.compile("(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})")
                          .matcher("Unknown error in node 00:00:5e:00:53:af. Terminating.")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
        System.out.println(Arrays.toString(matches)); // prints [00:00:5e:00:53:af]
    }
}

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result