swift - Swift - 替换字符串中完全匹配的字符/单词(不包含)
问题描述
我有一个这样
"c \\cdot c"
的字符串,它代表乳胶中的一个字符串。印在现实中会是c · c
。
现在我想替换它,c
因为它是一个变量。和
c = 2
结果一样2 · 2
。
我想过做类似的事情
let string = "c \\cdot c"
let replacingString = string.replacingOccurrences(of: "c", with: "2")
print(replacingString) // "2 \\2dot 2"
这不正是我的目标。但我希望应该存在一个非自制的解决方案,因为 Xcode 支持如下搜索模式:
“匹配词”应该可以解决问题。但是 swift 中是否已经提供了任何东西?如果不是,我会去做这样的事情。但这不是很方便:
let string = ":c: \\cdot :c:"
let replacingString = string.replacingOccurrences(of: ":c:", with: "2 ")
print(replacingString) // "2 \\cdot 2"
亲切的问候
继续
在 Dávid Pásztor 的投入之后,我正在尝试这个。只是为了分享一些实验结果。
let string = "c \\cdot c"
string.replacingOccurrences(of: "c", with: "2", options: .anchored, range: nil) // c \\cdot c
string.replacingOccurrences(of: "c", with: "2", options: .backwards, range: nil) // 2 \\cdot c
string.replacingOccurrences(of: "c", with: "2", options: .caseInsensitive, range: nil) // 2 \\2dot 2
string.replacingOccurrences(of: "c", with: "2", options: .diacriticInsensitive, range: nil) // 2 \\2dot 2
string.replacingOccurrences(of: "c", with: "2", options: .forcedOrdering, range: nil) // 2 \\2dot 2
string.replacingOccurrences(of: "c", with: "2", options: .literal, range: nil) // 2 \\2dot 2
string.replacingOccurrences(of: "c", with: "2", options: .numeric, range: nil) // 2 \\2dot 2
string.replacingOccurrences(of: "c", with: "2", options: .regularExpression, range: nil) // 2 \\2dot 2
最后
解决方法是:
let string = "c \\cdot c"
let replacingString = string.replacingOccurrences(of: "\\bc\\b", with: "2", options: .regularExpression)
print(replacingString) // "2 \\cdot 2"
非常感谢 Dávid Pásztor。
解决方案
您只需要使用replacingOccurences(of:with:options:)
并传递.regularExpression
给options
. 您还需要将正则表达式传递给of:
now 而不仅仅是传递要替换的子字符串。此处正确的正则表达式 if ,它在确保它只是您要匹配的字符而不是单词/表达式的一部分\\bc\\b
之前和之后匹配单词边界。c
c
c
let string = "c \\cdot c"
let replacingString = string.replacingOccurrences(of: "\\bc\\b", with: "2", options: .regularExpression)
print(replacingString) // "2 \\cdot 2"
推荐阅读
- symfony - 找不到对应的 Doctrine 对象
- sap-cloud-sdk - 如何在 SAP Cloud SDK 3.0 及更高版本中获取用户信息和权限
- ios - CBCentralManager,didConnect 外围设备:永远不会被调用
- uitextfield - Swiftui TextField onkeypress
- excel - VBA中的函数给我素数不起作用
- apache-kafka - 动物园管理员卡夫卡
- javascript - 想在按回车但重新加载时发送消息
- javascript - 为什么控制台显示typeError?
- wordpress - 如何从 Wordpress API 获取数据?
- go - 如何在数学/大浮点数中进行舍入?