import Foundation
let pattern = #"^config (dhcp|dns|router|interface) (?:ip|ipv4|id|bgp|name) (<[^>]*>|(?:\d+\.){3}\d+|[a-z]+ id \d+|\d+)( port| timeout| id|\s*)( <[^>]*>\s*| \d+\s*|\s*)$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
config dhcp ip <dhcp-ipaddress> port <dhcp-port-number>
config dhcp ip <dhcp-ipaddress> timeout <time-out-value>
config dhcp ipv4 <dhcp-ipaddress>
config dns ip <dns-ipaddress> port <dns-port-number>
config dns ip <dns-ipaddress> timeout <time-out-value>
config router bgp <bgp-number>
config interface id <interface-id>
config interface name <interface-name> id <interface-id>
config dhcp ip 1.1.1.1 port 8080
config dhcp ip 1.1.1.2 timeout 120
config dhcp ip 1.1.1.1 timeout 120
config dhcp ip 1.1.1.2 port 8080
config dhcp ipv4 1.1.1.3
config interface id 12
config interface name abc id 12
config interface id 13
config interface name xyz id 13
config dhcp ip 1.1.1.1 port 8080
config dhcp ip 1.1.1.1 timeout 120
config dhcp ip 1.1.1.2 timeout 120
config dhcp ip 1.1.1.2 port 8080
config dhcp ipv4 1.1.1.3
config interface id 12
config interface name abc id 12
config interface id 13
config interface name xyz id 13
"""#
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