import Foundation
let pattern = #"(\(?(0{1,2}|\+)\d{1,2}\)?)?(([ -]*\d+){8,20})+"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
https://asd.com/20441235534-aaaaaaaaaaa-
202460676
aasdasd 202460676
https://asd.com/20441235534
202460676-
10 text
1234 text
text 123
00491234567890
+491234567890
0123-4567890
0123 4567 789
0123 456 7890
0123 45 67 789
+490123 4567 789
+490123 456 7890
+49 123 45 67 789
123 4567 789
123 456 7890
123 45 67 789
+49 1234567890
+491234567890
0049 1234567890
0049 1234 567 890
(0049)1234567890
(+49)1234567890
(0049) 1234567890
(+49) 1234567890
text text (0049) 1234567890 text text
text text (+49) 1234567890 text text
"""#
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