【问题标题】:Swift - Replace exact matching Characters / Words in String (not containing)Swift - 替换字符串中完全匹配的字符/单词(不包含)
【发布时间】: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


    【解决方案1】:

    您只需要使用replacingOccurences(of:with:options:) 并将.regularExpression 传递给options。您现在还需要将正则表达式传递给of:,而不仅仅是传递要替换的子字符串。如果\\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"
    

    【讨论】:

    • 你好大卫。谢谢您的支持。您的解决方案非常有帮助。我建议修复打印行print(replacingString) // "2 \\cdot 2"。我确实在 Playground 上对其进行了测试,并注意到它是 print(replacingString) // ":2: \\cdot :2:" 只是为了防止一些混乱。亲切的问候
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多