import Foundation
let pattern = #"^(?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+)*) "#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
sh cdp nei
Capability Codes: R - Router, T - Trans-Bridge, B - Source-Route-Bridge
S - Switch, H - Host, I - IGMP, r - Repeater,
V - VoIP-Phone, D - Remotely-Managed-Device,
s - Supports-STP-Dispute
Device-ID Local Intrfce Hldtme Capability Platform Port ID
CHOD-MGMT-STACK.mhmp
mgmt0 129 S I WS-C2960X-48T Gig1/0/25
SPINE-401(FDO22041YMP)
Eth1/49 153 R S s N9K-C9336PQ Eth1/36
SPINE-402(FDO22081W5Y)
Eth1/50 176 R S s N9K-C9336PQ Eth1/36
IPN-2-CH(FDO221610MG)
Eth1/51 125 R S s N9K-C93180YC- Eth1/51
IPN-2-CH(FDO221610MG)
Eth1/52 125 R S s N9K-C93180YC- Eth1/52
IPN-1-KCP(FDO22152M53)
Eth1/54 143 R S s N9K-C93180YC- Eth1/54
Total entries displayed: 6
IPN-1-CH# sh lldp nei
Capability codes:
(R) Router, (B) Bridge, (T) Telephone, (C) DOCSIS Cable Device
(W) WLAN Access Point, (P) Repeater, (S) Station, (O) Other
Device ID Local Intf Hold-time Capability Port ID
SPINE-401 Eth1/49 120 BR Eth1/36
SPINE-402 Eth1/50 120 BR Eth1/36
IPN-2-CH Eth1/51 120 BR Ethernet1/51
IPN-2-CH Eth1/52 120 BR Ethernet1/52
IPN-1-KCP Eth1/54 120 BR Ethernet1/54
Total entries displayed: 5
"""##
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
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 Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression