import Foundation
let pattern = #"(?<=profile\.php\?id\=)(?<id>[0-9]+)|(?:(?<=\.com)|(?<=\.me)|(?<=\.co)|(?<=\.us))(?:(?:\/groups\/|\/)(?!profile\.php)(?<username>[\w\.\_]+))"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
https://www.facebook.com/hung.le054
https://www.facebook.com/groups/j2team.community/?ref=nf_target&fref=nf&__xts__%5B0%5D=68.ARCufAkDYLfgBw09Ctl9HKUd8wMYIaATKYHE-9guWWpCGu86iH8k0p4Qx8BxlXEEJMW8shzzodIckx0qvnBg94kwMe3uOIPnjE9s6neoXwFX8kBJsWBpF-Ej8oXpGdiIu6sf9cg9tyeq&__tn__=C-R
https://www.facebook.com/NoExit.GoEXID/?hc_ref=ARQCFBLI4l-ciKCPEGazrn4_8WTxAulTr9a7XgMTgi_OKA_Iad1-hMzdD2z0snaq3BE&fref=nf&__xts__%5B0%5D=68.ARAUlT1DqV2wkn3VWI7belmtRn5k9XXk05WUw1Gl88lm2CDjGSmYX0zI_p8A19EG2w6iWF3t0gZN-GurkpGl05KGdS5Xv8lC__sOmlxD8Jz5CrhOjbz1ThvYtiZA3yzk4P66-V5BjDty&__tn__=kCH-R
https://www.facebook.com/profile.php?id=100010004806283&fref=pb&hc_location=friends_tab
"""#
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