import Foundation
let pattern = #"HTTP\/\d\.\d\s(\d{3})"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
HTTP/1.1 302 See other
Date: Tue, 17 Feb 2015 20:20:48 GMT
Server: Apache
X-Powered-By: PHP/5.5.21
Set-Cookie: 5e8627afafd16a920dac4dbb644715a5=ue1gprimq6rb5r4qsb8sk28jb2; path=/; HttpOnly
Location: http://fake.dk/da/
Connection: close
Content-Type: text/html; charset=utf-8
Set-Cookie: SERVERID=; path=/
HTTP/1.1 200 OK
Date: Tue, 17 Feb 2015 20:20:48 GMT
Server: Apache
X-Powered-By: PHP/5.5.21
Set-Cookie: 76726d50abd3edd601ecfbc19fe61c87=da-DK; path=/
Set-Cookie: 76726d50abd3edd601ecfbc19fe61c87=da-DK
P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"
Expires: Mon, 1 Jan 2001 00:00:00 GMT
Last-Modified: Tue, 17 Feb 2015 20:20:48 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Connection: close
Content-Type: text/html; charset=utf-8
Set-Cookie: SERVERID=; path=/
<!doctype html>
<html lang="da">
<head>
</head>
<body>
</body>
</html>
"""#
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