find mac addresses in a string using regex in typescript

To find MAC addresses in a string using regular expressions in TypeScript, you can use the following code:

index.ts
const regex = /(?:[0-9a-fA-F]:?){12}/g;
const inputString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu felis quis sapien maximus rhoncus 12:34:56:78:90:ab 00-11-22-33-44-55 12:34:56:78:90:AB. Sed ac nibh vitae orci posuere mollis. Aliquam finibus turpis eu odio consequat consequat.";

const macAddresses = inputString.match(regex);
console.log(macAddresses);
381 chars
6 lines

Explanation of the regular expression used (/(?:[0-9a-fA-F]:?){12}/g):

  • (?:...) is a non-capturing group
  • [0-9a-fA-F] matches any hex digit (case insensitive)
  • :? matches an optional : character
  • {12} specifies that the previous group should be matched exactly 12 times
  • /g at the end enables a global search (i.e. it will find all matches in the input string)

The code above uses the match method to find all occurrences of the regular expression in the input string. It returns an array containing all the matches (in this case, the MAC addresses found in the input string).

Note that this regular expression will only match MAC addresses in the standard format (i.e. 12:34:56:78:90:AB or 00-11-22-33-44-55). If you need to match other formats (e.g. with spaces instead of colons/hyphens), you'll need to modify the regular expression accordingly.

gistlibby LogSnag