首页 > 解决方案 > 用于在字符串中搜索格式说明符的 Swift 正则表达式

问题描述

我需要帮助来编写快速正则表达式以在字符串中查找任何格式说明符。

例如。

“我是%@。我的年龄是%d,身高是%.02f。”

我需要以粗体查找所有子字符串并将其替换为“匹配”

下面是我的代码

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)

和输出

I am MATCH. My age is MATCH and my height is %.02f. (%@)

它没有找到%.02f和最后一个带括号的%@ 。

提前致谢!

标签: iosswiftregex

解决方案


首先,您必须替换反转的匹配项,否则您将遇到索引问题。

一个可能的模式是

%([.0-9]+)?[@df]

它还考虑(可选)小数位说明符。

var description = "I am %@. My age is %d and my height is %.02f. (%@)"
let pattern = "%([.0-9]+)?[@df]"
let regex = try NSRegularExpression(pattern: pattern)
let nsrange = NSRange(description.startIndex..., in: description)

for match in regex.matches(in: description, range: nsrange).reversed() {
    let range = Range(match.range, in: description)!
    description.replaceSubrange(range, with: "MATCH")
}
print(description)

推荐阅读