SlothGR SlothGR - 3 months ago 14
Python Question

Python regex extract MAC addresses from string

I need help writing a regular expression, using the python

re
engine to:


  1. Extract all MAC addresses from a text file

  2. Extract all strings with the following format:
    foo bar ... MAC:ADDRESS ... baz bat \r\n



Thanks in advance!

I tried the following to extract MAC addresses, without luck:

import re
p = re.compile(ur'((?:(\d{1,2}|[a-fA-F]{1,2}){2})(?::|-*)){6}')
test_str = u"TEXT WITH SOME MAC ADDRESSES 00:24:17:b1:cc:cc TEXT CONTINUES WITH SOME MORE TEXT 20:89:86:9a:86:24"

found = re.findall(p, test_str)
for a in found:
print a

Answer

I have concocted the following: ([0-9a-fA-F]:?){12} to match MAC addresses in the text.

Here is how it is supposed to work:

  • [0-9a-fA-F] matches the characters used to represent hexadecimal numbers
  • :? matches an optional colon
  • (...){12} - all of this is then grouped and repeated 12 times. 12 because a MAC address consists of 6 pairs of hexadecimal numbers, separated by a colon

You can see it in action here .

The Python code then becomes:

import re
p = re.compile(ur'(?:[0-9a-fA-F]:?){12}')
test_str = u"TEXT WITH SOME MAC ADDRESSES 00:24:17:b1:cc:cc TEXT CONTINUES WITH SOME MORE TEXT 20:89:86:9a:86:24"

re.findall(p, test_str)

Producing as a result:

[u'00:24:17:b1:cc:cc', u'20:89:86:9a:86:24']
Comments