【发布时间】:2021-02-19 12:18:22
【问题描述】:
我有一个这样的字符串
"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。
【问题讨论】:
标签: swift string replace character