import Foundation
let pattern = #"^http[s]?:\/\/www\.linkedin\.com\/(?:in|pub|public-profile\/in|public-profile\/pub)\/(?:[\w]{6}-[\w]{1,}-[\w]+)$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
https://www.linkedin.com/in/XXXXXX-XXXXX-55301b41
https://www.linkedin.com/pub/XXXXXX-XXXXX-55301b41
https://www.linkedin.com/public-profile/in/XXXXXX-XXXX-b82a7b10a
https://www.linkedin.com/public-profile/pub/XXXXXX-XXXX-b82a7b10a
https://www.linkedin.com/in/xxxx-xxxx-ab85a328/%7Bcountry%3Dde%2C+language%3Dde%7D?trk=people-guest_profile-result-card_result-card_full-click
https://www.linkedin.com/edu/school?id=18987
https://www.linkedin.com/in/xxxx-xxxx-55301b41/de
https://www.linkedin.com/pub/xxxxx-xxxxx/98/b7a/22b
https://it.linkedin.com/public-profile/in/xxxx-xxxxx-80520667?challengeId=AQEV3tHveORYsAAAAXQqx1N3bZ7fd44s5ngegJp6rC0UoWvhG2LtAhhgld8h3QyBxorfcLL2iuvK4xh_UKoGguxvX6sFx_nnZA&submissionId=7bc972ed-bfd1-2e16-c395-ad35cb550117
"""#
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