简体   繁体   中英

Javascript: Extract MAC codes from freeform text using Regex

I'm attempting to write a Chrome Extension that will scan a web page for valid MAC codes and push each in to an array. I have a regex that validates the MAC but I can't get it to match multiple codes.

Here is a quick snippet of my code :

var regex = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/;
var body = document.body.innerText.replace(/\n/g,' ');

console.log(body.match(regex));

var occur = regex.exec(body);

console.log(occur);

Many thanks.

MAC addresses are typically 6 groups of two hexadecimal digits (0-9,A,B,C,D,E,F), separated either by colons (:) or hyphens (-).

Are you looking for this?

/([0-9A-F]{2}(?:[:-][0-9A-F]{2}){5})/g

Online demo

Get the matched group from index 1.

Remove the beginning of string ^ and end of string $ anchors and use the g ( global ) modifier..

var regex = /([0-9A-F]{2}[:-]){5}([0-9A-F]{2})/g

As stated in the documentation...

The g modifier is used to perform a global match (find all matches rather than stopping after the first match)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM