I was wondering if there is support in Swift regex to directly replace the substring value of a named captured?
// Capture a 12-hour time substring and replace it with a converted 24-hour time substring
// Ex: "swimming lessons are at 11AM and 1PM" -> "swimming lessons are at 11:00 and 13:00"
var lessonTimesString = "swimming lessons are at 11AM and 1PM"
let timeRef = Reference(Substring.self)
let amPmRef = Reference(Substring.self)
let regex = Regex {
Capture(as: timeRef) {
OneOrMore(.digit)
}
Capture(as: amPmRef) {
ChoiceOf {
"AM"
"PM"
}
}
}
for match in lessonTimesString.matches(of: regex) {
let time = Int(match[timeRef])!
let amPm = String(match[amPmRef])
var timeConverted = time
if time == 12 {
if amPm == "AM" {
timeConverted = 0
}
} else {
if amPm == "PM" {
timeConverted = time + 12
}
}
let timeConvertedString = "\(timeConverted):00"
// how could I directly replace the named capture timeRef substring with timeConvertedString and amPmRef substring with an empty string?
}