import Foundation
let pattern = ##"^(?P<scheme>http(?:s)?:\/\/)?(?P<www>www\d?\.)?(?P<domain>\b(?!www\d?\.)[a-z\d\-]+(?:\.[a-z\d\-]{2,})+)(?P<port>:\d{1,5})?(?P<path>\/(?:[-a-zA-Z0-9._~!$&\'()*+,;=:@]|%[0-9a-fA-F]{2})*)*(?P<query_fragm>[?#&][\/\_\-\&\%\?\#\+\=\.:a-zA-Z\d]*)*$"##
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
http://example.com
https://www.example.com
http://example.com/path
https://www.example.com/path
http://example.com/path?query=1
https://www.example.com/path?query=1
http://example.com/path#fragment
https://www.example.com/path#fragment
http://example.com:8080
https://www.example.com:8080
http://subdomain.example.com
https://www.subdomain.example.com
http://subdomain.example.com/path
https://www.subdomain.example.com/path
http://subdomain.example.com/path?query=1
https://www.subdomain.example.com/path?query=1
http://subdomain.example.com/path#fragment
https://www.subdomain.example.com/path#fragment
http://subdomain.example.com:8080
https://www.subdomain.example.com:8080
http://example.org
https://www.example.org
http://example.org/path
https://www.example.org/path
http://example.org/path?query=1
https://www.example.org/path?query=1
http://example.org/path#fragment
https://www.example.org/path#fragment
http://example.org:8080
https://www.example.org:8080
http://subdomain.example.org
https://www.subdomain.example.org
http://subdomain.example.org/path
https://www.subdomain.example.org/path
http://subdomain.example.org/path?query=1
https://www.subdomain.example.org/path?query=1
http://subdomain.example.org/path#fragment
https://www.subdomain.example.org/path#fragment
http://subdomain.example.org:8080
https://www.subdomain.example.org:8080
http://example.net
https://www.example.net
http://example.net/path
https://www.example.net/path
http://example.net/path?query=1
https://www.example.net/path?query=1
http://example.net/path#fragment
https://www.example.net/path#fragment
http://example.net:8080
https://www.example.net:8080
"""##
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