import re
regex = re.compile(r"""
\b(
# MAC address like xx:xx:xx:xx:xx:xx
[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}
|
# MAC address like xx-xx-xx-xx-xx-xx
[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}
|
# MAC address like xxxx.xxxx.xxxx
[0-9a-f]{4}\.[0-9a-f]{4}\.[0-9a-f]{4}
|
# IPv4 address in dotted-quad format
# Not a lot of value for our needs in checking range of each octet
# Need to be more mindful of performance here anyway.
\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
)\b
""", flags=re.IGNORECASE | re.VERBOSE)
test_str = ("192.168.1.2\n"
"10.0.0.0\n"
"ff:ff:ff:ff:ff:ff\n"
"FF-FF-FF-FF-FF-FF\n"
"FFFF.FFFF.FFFF\n"
"ffff.ffff.ffff\n"
"blah127.0.0.1haha\n"
"foo127.0.0.1\n\n\n")
subst = "\\1"
result = regex.sub(subst, test_str, count=1)
if result:
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html