ios - 用于在字符串中搜索格式说明符的 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和最后一个带括号的%@ 。
提前致谢!
解决方案
首先,您必须替换反转的匹配项,否则您将遇到索引问题。
一个可能的模式是
%([.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)
推荐阅读
- javascript - 如何在使用 Nuxt 的 fetch() 挂钩获取数据时防止模板错误
- bash - 将 grep 的多行输出分配给变量
- html - Django urls 关系
- react-native - 如何解决项目错误:元素类型无效?
- powerbi - 在 DAX 中计算多个条件下的记录
- vue.js - Vuex 状态或 getter 总是返回 undefined
- php - 如何为图像设置 WordPress 无 cookie 域?
- c# - 在 LINQ 内部连接中保留空值
- c - 静态内联 vs -finline-functions
- c# - Unity c# Photon - 设置 PhotonNetwork.Instantiate 对象的父级