Python正则表达式从字符串中提取MAC地址 [英] Python regex extract MAC addresses from string
本文介绍了Python正则表达式从字符串中提取MAC地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要帮助编写正则表达式,使用 python re
引擎:
I need help writing a regular expression, using the python re
engine to:
- 从文本文件中提取所有 MAC 地址
- 使用以下格式提取所有字符串:
foo bar ... MAC:ADDRESS ... baz bat \r\n
提前致谢!
我尝试了以下方法来提取 MAC 地址,但运气不佳:
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
推荐答案
我编造了以下内容:([0-9a-fA-F]:?){12}
以匹配 MAC 地址在正文中.
I have concocted the following: ([0-9a-fA-F]:?){12}
to match MAC addresses in the text.
这是它应该如何工作:
[0-9a-fA-F]
匹配用于表示十六进制数的字符:?
匹配一个可选的冒号(...){12}
- 然后将所有这些分组并重复 12 次.12 因为一个 MAC 地址由 6 对十六进制数字组成,用冒号分隔
[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 .
Python 代码变为:
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)
生产结果:
[u'00:24:17:b1:cc:cc', u'20:89:86:9a:86:24']
这篇关于Python正则表达式从字符串中提取MAC地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文