Python regex extract MAC addresses from string -
i need help writing regular expression, using python re engine to:
foo bar ... mac:address ... baz bat \r\n thanks in advance!
i tried next extract mac addresses, without luck:
class="lang-python prettyprint-override">import re p = re.compile(ur'((?:(\d{1,2}|[a-fa-f]{1,2}){2})(?::|-*)){6}') test_str = u"text mac addresses 00:24:17:b1:cc:cc text continues more text 20:89:86:9a:86:24" found = re.findall(p, test_str) in found: print
i have concocted following: ([0-9a-fa-f]:?){12} match mac addresses in text.
here how supposed work:
[0-9a-fa-f] matches characters used represent hexadecimal numbers :? matches optional colon (...){12} - of grouped , repeated 12 times. 12 because mac address consists of 6 pairs of hexadecimal numbers, separated colon you can see in action here .
the python code becomes:
class="lang-python prettyprint-override">import re p = re.compile(ur'(?:[0-9a-fa-f]:?){12}') test_str = u"text mac addresses 00:24:17:b1:cc:cc text continues more text 20:89:86:9a:86:24" re.findall(p, test_str) producing result:
class="lang-python prettyprint-override">[u'00:24:17:b1:cc:cc', u'20:89:86:9a:86:24'] python regex
No comments:
Post a Comment