import Foundation
let pattern = #"\b((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)+(?:\/{1}((?:[0-9])|(?:[1-2][0-9])|(?:3[0-2]))\b)?)|((?:[a-f0-9:]+:+)+(?:[a-f0-9])+(?:\/{1}((?:(?:3[0-2]|[12]?\d)))\b)?)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
192.168.1.1 192.168.2.1
192.168.3.1
"192.168.10.1", "192.168.10.257" 10.0.0.1, 8.8.8.8
not_an_ip "192.168.0.1 10.9.9.0
random text here
127.0.0.1
192.168.23.12
2001:db8::
::1234:5678
2001:db8::1234:5678
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468
192.168.3.1/32
10.0.0.0/0
12.10.0.0/24
10.0.0.0/24
10.0.0.0/99
1.1.1.25/23
0.0.0.0/3
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468/0
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468/9
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468/10
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468/15
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468/22
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468/32
54a9:1437:0fbd:e763:8a47:fccd:b09b:e468/41
"""#
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