import Foundation
let pattern = #"\b(127\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|0?10\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|172\.0?1[6-9]\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|172\.0?2[0-9]\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|172\.0?3[01]\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|192\.168\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|169\.254\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|::1|[fF][cCdD][0-9a-fA-F]{2}(?:[:][0-9a-fA-F]{0,4}){0,7}|[fF][eE][89aAbB][0-9a-fA-F](?:[:][0-9a-fA-F]{0,4}){0,7})(?:\/([789]|1?[0-9]{2}))?\b"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
# loopback
127.0.0.0
127.0.0.0000 # only three digits supported here
# A
10.0.0.1/10
10.255.22.33
# B
172.17.100.155/32
# C
192.168.1.1
192.168.1.255
# IPv6
fc00:833e:d648:f196:5c6c:1d9a:a14b:0d59
fc01:67e5::6a66:34a7
FC02:5fcf:e093:bb10:ce77:b5c9::/112
fc03:49bd:b7c1:5685:fa0a:87e9::2/128
fc04:::2 hmpf
# Public IP addresses
0de9:b022:883f:2c3c:7dba:a184:7576:4531
04e4:e53b:0c2f:2990:27ad:0464:6dd3:b6b3
0319:3b4a:546e:d480:4814:f885:3396:bba2
5394:03f5:606f:273e:e343:d94a:610a:3f2e
63cd:ad1f:7ffb:62c7:cc17:6e20:9b59:2f7d
# More "crap"
30.168.1.255.1
127.1
192.168.1.256
-1.2.3.4
1.1.1.1.
3...3
255.255.255.255
0.0.0.0
1.1.1.01
192.99.16.30
# decimal vs. octal mix
172.032.33.33
172.033.33.33
# octal - not supported here
0254.0021.0062.0041
# link-local addresses IPv4
169.254.1.0
169.254.254.255
# link-local addresses IPv6
fe90:1234::/64
feaf:ffff::/128
febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff
"""##
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