There are probably simpler alternatives but the following will work:
let myText = "ABIZCDEIZIZ"
let result = myText
// replace any I at 3rd or 4th position with 1
.replacingOccurrences(of: "(?<=^.{2,3})I", with: "1", options: .regularExpression)
// replace any Z at 3rd or 4th position with 2
.replacingOccurrences(of: "(?<=^.{2,3})Z", with: "2", options: .regularExpression)
print(result) // AB12CDEIZIZ
or, without regular expressions:
let result = String(myText.enumerated().map {
guard (2...3).contains($0.offset) else { return $0.element }
switch $0.element {
case "I":
return "1"
case "Z":
return "2"
default:
return $0.element
}
})
print(result)
or moving the logic together:
let result = String(myText.enumerated().map {
switch $0.element {
case "I" where (2...3).contains($0.offset):
return "1"
case "Z" where (2...3).contains($0.offset):
return "2"
default:
return $0.element
}
})