# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"^(?P<hostname>[\w-_]+)\s+(?P<localInterface>[A-Za-z]+\d+(?:\/\d+)*)\s+(?P<holdTime>\d+)\s+(?P<capabilities>[A-Z]+)\s+(?P<remoteInterface>[A-Za-z]+\d+(?:\/\d+)*) "
test_str = ("sh cdp nei\n\n"
"Capability Codes: R - Router, T - Trans-Bridge, B - Source-Route-Bridge\n"
" S - Switch, H - Host, I - IGMP, r - Repeater,\n"
" V - VoIP-Phone, D - Remotely-Managed-Device,\n"
" s - Supports-STP-Dispute\n\n"
"Device-ID Local Intrfce Hldtme Capability Platform Port ID\n"
"CHOD-MGMT-STACK.mhmp\n"
" mgmt0 129 S I WS-C2960X-48T Gig1/0/25 \n"
"SPINE-401(FDO22041YMP)\n"
" Eth1/49 153 R S s N9K-C9336PQ Eth1/36 \n"
"SPINE-402(FDO22081W5Y)\n"
" Eth1/50 176 R S s N9K-C9336PQ Eth1/36 \n"
"IPN-2-CH(FDO221610MG)\n"
" Eth1/51 125 R S s N9K-C93180YC- Eth1/51 \n"
"IPN-2-CH(FDO221610MG)\n"
" Eth1/52 125 R S s N9K-C93180YC- Eth1/52 \n"
"IPN-1-KCP(FDO22152M53)\n"
" Eth1/54 143 R S s N9K-C93180YC- Eth1/54 \n\n"
"Total entries displayed: 6\n\n"
"IPN-1-CH# sh lldp nei\n\n"
"Capability codes:\n"
" (R) Router, (B) Bridge, (T) Telephone, (C) DOCSIS Cable Device\n"
" (W) WLAN Access Point, (P) Repeater, (S) Station, (O) Other\n"
"Device ID Local Intf Hold-time Capability Port ID \n"
"SPINE-401 Eth1/49 120 BR Eth1/36 \n"
"SPINE-402 Eth1/50 120 BR Eth1/36 \n"
"IPN-2-CH Eth1/51 120 BR Ethernet1/51 \n"
"IPN-2-CH Eth1/52 120 BR Ethernet1/52 \n"
"IPN-1-KCP Eth1/54 120 BR Ethernet1/54 \n"
"Total entries displayed: 5")
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
# 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