# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = 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
"""
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"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 1, re.IGNORECASE | re.VERBOSE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
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