Skip to content

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

Leave a Reply

Your email address will not be published.