find mac addresses in a string using regex in javascript

To find MAC addresses in a string using regex in JavaScript, you can use the following pattern:

index.tsx
const regex = /(?:[0-9a-fA-F]{2}[:.-]?){5}[0-9a-fA-F]{2}/g;
const text = 'This is a sample string 00:11:22:33:44:55 and another one 11-22-33-44-55-66';
const macAddresses = text.match(regex);

console.log(macAddresses); // ["00:11:22:33:44:55", "11-22-33-44-55-66"]
266 chars
6 lines

The pattern /(?:[0-9a-fA-F]{2}[:.-]?){5}[0-9a-fA-F]{2}/g matches any sequence of characters that contains 5 groups of hexadecimal digits of length 2 separated by either a colon, a dot, or a hyphen, followed by the sixth group of hexadecimal digits also of length 2.

The g flag is used to match all instances of the pattern in the string.

The match() method is used to return an array of all the matches found in the string.

This code can be used in any JavaScript application or environment that supports regex pattern matching.

gistlibby LogSnag