I need help to write the swift regex to find any format specifier in a string.
Eg.
"I am %@. My age is %d and my height is %.02f."
I need to find all sub-strings in bold and replace them with 'MATCH'
Below is my code
var description = "I am %@. My age is %d and my height is %.02f. (%@)"
let pattern = "(%[@df])"
let regex = try NSRegularExpression(pattern: pattern, options: [])
let nsrange = NSRange(description.startIndex..<description.endIndex, in: description)
while let match = regex.firstMatch(in: description, options: [], range: nsrange) {
description = (description as NSString).replacingCharacters(in: match.range, with: "MATCH")
}
print(description)
and output
I am MATCH. My age is MATCH and my height is %.02f. (%@)
It did not find %.02f and last %@ with paranthesis.
Thanks in advance!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…