import Foundation
let pattern = #"""
^
(?(DEFINE)
(?<hex4>[0-9A-Fa-f]{1,4})
(?<hex4_>(?&hex4):)
(?<_hex4>:(?&hex4))
(?<byte>
(25[0-5])|(2[0-4]\d)|(1\d{2})|([1-9]\d)|\d
)
(?<ipv4>
((?&byte)\.){3}(?&byte)
)
)
(((?&hex4_){7}(?&hex4))
|((?&hex4_){5}(?&_hex4))
|((?&hex4_){4}(?&_hex4){1,2})
|((?&hex4_){3}(?&_hex4){1,3})
|((?&hex4_){2}(?&_hex4){1,4})
|((?&hex4_){1}(?&_hex4){1,5})
|(:(?&_hex4){1,6})
|((?&hex4_){1,6}:)
|((?&hex4_){6}(?&ipv4))
|((?&hex4_){3}(?&_hex4):(?&ipv4))
|((?&hex4_){2}(?&_hex4){1,2}:(?&ipv4))
|((?&hex4_){1}(?&_hex4){1,3}:(?&ipv4))
|((?&hex4_){1,4}:(?&ipv4))
|(:(?&_hex4){0,4}:(?&ipv4))
)$
"""#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .allowCommentsAndWhitespace])
let testString = #"""
;valid
2001:db8:0:0:0:0:2:1
2001:db8::2:1
2001:db8:0:1:1:1:1:1
2001:db8:a0b:12f0::1
2001:0db8:0a0b:12f0:0000:0000:0000:0001
3731:54:65fe:2::a7
::10.0.0.3
::ffff:0:10.0.0.3
0064:ff9b:0000:0000:0000:0000:18.52.86.120
0064:ff9b::0000:18.52.86.120
0064:ff9b::18.52.86.120
;invalid
2001:db8::1:1:1:1:1
10.0.0.3
::256.127.0.1
::127.0.0.01
::127.0.0
"""#
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