import Foundation
let pattern = #"[^\d]((\+49|0049|0)1[567]\d{1,2}([ \-/]*\d){7})(?!\d)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ####################################"""
################################### This is allowed ##########################
+49 15207930698
+49 15207955279
+49 915175461907
+4915207829969
+4915368831169
+491771399487
+4917697300278
+4915902955865
+491771789427
+4917697400179
+4915903904567
+4915902944599
+491739341284
+4915902944599
+4915903904567
The number +491739341284 with some text
Germany +4915255687865Total SMS: 6758
This number 015731294508 we need!
015731294508
015735995842
015168433343
Here:015731294508Hallo
Here:015731294508
<td>01573 / 1294-508</tr>
<td>015731294508</tr>
Eine Nummer: 01515 84 333 78
Wichtige Nummer:015731294508.
Noch eine Nummer-015731294508,
015731294508Hier
<td>01573 1294 508</tr>
################################### This is NOT allowed ##########################
012345678901234
123w345345345345
0123456789101191919
+4915902
+491590123
+4915903567
+49177178796
+49159039012341
+491590345985412
Invalid number +491590345985412 within text
+12127319863
+13322014056
+12126712234
+427532697710
+417868150810
+287533002875
+49 1739341284
(+49) 1739341284
+49 17 39 34 12 84
+49 (1739) 34 12 84
+(49) (1739) 34 12 84
+49 (1739) 34-12-84
"""####################################
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