You can use NSDataDetector
to detect dates with any format in your string, get its NSRange, convert to Range<String.Index>
, check if the string found on that range matches the desired date format and if it matches just insert the new line character at range.lowerBound
:
extension Formatter {
static let customDate: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "dd/MM/yy" // or "MM/dd/yy"
return dateFormatter
}()
}
Playground testing:
var configstring = "01/01/19 AAA BBB CCC DDD EEE FFF GGG HHH III JJJ KKK 0000 1111 0000 0000 1111 0000 0000 LLLL 01/02/19 MMM NNN OOO PPP RRR SSS TTT UUU 0000 1111 1111 0000 1111 1111 0000 1111 0000 0000 WWWW "
do {
let ranges = try NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)
.matches(in: configstring, range: .init(configstring.startIndex..., in: configstring))
.compactMap { Range<String.Index>($0.range, in: configstring) }
for range in ranges.reversed() {
// check if the date found matches the desired format
if let date = Formatter.customDate.date(from: String(configstring[range])) {
print("date match:", date)
configstring.insert("\n", at: range.lowerBound)
}
}
} catch {
print(error)
}
print(configstring) // "\n01/01/19 AAA BBB CCC DDD EEE FFF GGG HHH III JJJ KKK 0000 1111 0000 0000 1111 0000 0000 LLLL \n01/02/19 MMM NNN OOO PPP RRR SSS TTT UUU 0000 1111 1111 0000 1111 1111 0000 1111 0000 0000 WWWW \n"
Or using regular expression
let pattern = "\\d{2}/\\d{2}/\\d{2}" // or "(\\d{2}/){2}\\d{2}" or "\\d{2}(/\\d{2}){2}"
var configstring = "01/01/19 AAA BBB CCC DDD EEE FFF GGG HHH III JJJ KKK 0000 1111 0000 0000 1111 0000 0000 LLLL 01/02/19 MMM NNN OOO PPP RRR SSS TTT UUU 0000 1111 1111 0000 1111 1111 0000 1111 0000 0000 WWWW "
var startIndex = configstring.startIndex
while let range = configstring[startIndex...].range(of: pattern, options: .regularExpression) {
// check if the date found matches the desired format
if let date = Formatter.customDate.date(from: String(configstring[range])) {
print("date match:", date)
configstring.insert("\n", at: range.lowerBound)
}
startIndex = range.upperBound
}
print(configstring) // "\n01/01/19 AAA BBB CCC DDD EEE FFF GGG HHH III JJJ KKK 0000 1111 0000 0000 1111 0000 0000 LLLL \n01/02/19 MMM NNN OOO PPP RRR SSS TTT UUU 0000 1111 1111 0000 1111 1111 0000 1111 0000 0000 WWWW \n"