Use the limiting quantifier instead of repeating a character or pattern multiple times

The MAC address of a computer is a unique identifier assigned to network interfaces at the time of manufacturing. MAC addresses are 6 bytes or 48 bits in length and are written in the nn:nn:nn:nn:nn:nn format, where each n represents a hexadecimal digit. To match a MAC address, one can write the following regex:

^[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}$ 

However, it is much cleaner and more readable to write the regex as follows:

^(?:[A-F\d]{2}:){5}[A-F\d]{2}$ 

Note how short and readable this regex pattern has become when compared to the previous regex.

Get Java 9 Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.