1
votes

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
4
You said you tried something, why not post some code here? - JoErNanO
If you have regex questions, providing several example inputs and expected outputs helps tremendously. - Cory Kramer
What have you attempted so far? - Andy_A̷n̷d̷y̷
Edited the question guys - SlothGR
Have nominated for reopening.The question seems meeting all guidlines now - vks

4 Answers

8
votes

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(r'(?:[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']
6
votes
([0-9a-f]{2}(?::[0-9a-f]{2}){5})

Try this.See demo.

http://regex101.com/r/kP8uF5/5

import re
p = re.compile(ur'([0-9a-f]{2}(?::[0-9a-f]{2}){5})', re.IGNORECASE)
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)
2
votes

I had to match MAC addresses too and this worked:((?:[\da-fA-F]{2}[:\-]){5}[\da-fA-F]{2})

I tested it with this live regex tester: https://regex101.com/#python It had a very nice breakdown of what each piece of regex did.

0
votes
text = "this is aa:bb:cc:dd:01:02 test for aa-bb-cc-dd-ee-ff and AABBCCDDEEFF is a mac address without separator"

let us extract mac addresses

def extract_mac_address(text):
    pattern = '(([0-9a-fA-F]{2}[:]){5}([0-9a-fA-F]{2})|([0-9a-fA-F]{2}[-]){5}([0-9a-fA-F]{2})|[0-9a-fA-F]{12})'
    mac_addr_list = re.findall(pattern, text)
    return list(map(lambda x: x[0], mac_addr_list))


print(extract_mac_address(text))

and output is ['aa:bb:cc:dd:01:02', 'aa-bb-cc-dd-ee-ff', 'AABBCCDDEEFF']