1

I have a node.js app that needs to extract a MAC address from a string.

var str = "bridge=vmbr1,virtio=32:65:63:62:36:35";

The problem lies in the fact that the string is dynamic - it is not always in that format. It could also appear as...

var str = "bridge=vmbr1,virtio=32:65:63:62:36:35,firewall=1";

...among many other variations. For that reason, using something like split or substring won't work. I assume I might need to use some regex to extract just the 32:65:63:62:36:35 part from the string.

Any help is appreciated.

user1710563
  • 387
  • 2
  • 7
  • 18

2 Answers2

1

Try this:

str = "bridge=vmbr1,virtio=32:65:63:62:36:35,firewall=1";
str.match(/([0-9A-F]{2}:?){6}/g);

// output
// ["32:65:63:62:36:34"]

This will even work with multiple MACs in a single string.

str = "bridge=vmbr1,virtio=32:65:63:62:36:35,firewall=1,foo=32:65:63:62:36:39,bar=32:65:63:62:36:38";
str.match(/([0-9A-F]{2}:?){6}/g);

// output
// ["32:65:63:62:36:34","32:65:63:62:36:39","32:65:63:62:36:38"]
Michael Ambrose
  • 992
  • 6
  • 11
1
/([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})/

Regex to match standards group mac public listing IEEE Std 802.1D and IEEE Std 802.1Q Reserved Addresses.

The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits, separated by hyphens - or colons :


string = "bridge=vmbr1,virtio=32:65:63:62:36:35,firewall=1";
result = string.match(/([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})/);
document.write(result[0])
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268