Java RegEx – Validate MAC Address

Java RegEx – Validate MAC Address example shows how to validate a MAC address using a regex pattern in Java. There is a couple of regex patterns using which we can validate it.

How to validate a MAC address using a regex pattern in Java?

A Media Access Control address, commonly known as a MAC address, is a unique id assigned to a network device to use for communication within the network. The most common format of MAC address has 6 groups of 2 hexadecimal digits either separated by a hyphen or a colon as given below. Valid hexadecimal digits are 0 to 9 and a to f in upper or lower case.

Here is the regex pattern to validate that.

Where,

Let’s try this regex with some sample MAC addresses.

Output

If the address has both “:” and “-” (e.g. “AB-AC-12:3F:BD:C5”), the above-given pattern will say it is valid, while it is not. In order to fix that, we need to change our pattern as given below.

I have basically joined two kinds of separator patterns using a regex OR condition (“|”).

Now, many manufactures do not follow these formats, for example, some displays MAC addresses without any separators. So if you want to cover that as well, here is the pattern that will validate the address in any format.

Output

Before matching the address with the pattern, I have replaced all non-hexadecimal characters with empty strings, thus removing them. The pattern is also simplified and just checks whether the address has 12 hexadecimal digits or not. As you can see from the output, regardless of the format, as long as the address has 12 valid hexadecimal digits the pattern will validate it as a valid address.

If you want to learn more about regex, please visit the Java regex tutorial.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *