O'Reilly logo

Java 9 Regular Expressions by Anubhava Srivastava

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required