首页 > 解决方案 > 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 支持如下搜索模式: 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。

标签: swiftstringreplacecharacter

解决方案


您只需要使用replacingOccurences(of:with:options:)并传递.regularExpressionoptions. 您还需要将正则表达式传递给of:now 而不仅仅是传递要替换的子字符串。此处正确的正则表达式 if ,它在确保它只是您要匹配的字符而不是单词/表达式的一部分\\bc\\b之前和之后匹配单词边界。ccc

let string = "c \\cdot c"
let replacingString = string.replacingOccurrences(of: "\\bc\\b", with: "2", options: .regularExpression)
print(replacingString)  // "2 \\cdot 2"

推荐阅读