【问题标题】:Combine multiple replacingOccurrences() with Swift将多个 replaceOccurrences() 与 Swift 结合使用
【发布时间】:2020-07-18 12:23:43
【问题描述】:

我有一个字符串,我想为特定字符添加反斜杠,因为我使用 markdown 并且不想添加不需要的样式。

我尝试制作一个函数,它正在工作,但我猜它效率不高:

func escapeMarkdownCharacters(){
      let myString = "This is #an exemple #of _my_ * function"
      var modString = myString.replacingOccurrences(of: "#", with: "\\#")
      modString = modString.replacingOccurrences(of: "*", with: "\\*")
      modString = modString.replacingOccurrences(of: "_", with: "\\_")
      print(modString) // Displayed: This is \#an exemple \#of \_my\_ \* function 
}

我希望只有一个适用于多个角色的“替换事件”。我想我可以用正则表达式做到这一点,但我不知道怎么做。如果您有想法,请与我分享。

【问题讨论】:

    标签: ios swift regex string swift5


    【解决方案1】:

    你可以使用

    var modString = myString.replacingOccurrences(of: "[#*_]", with: "\\\\$0", options: [.regularExpression])
    

    使用原始字符串文字:

    var modString = myString.replacingOccurrences(of: "[#*_]", with: #"\\$0"#, options: [.regularExpression])
    

    结果:This is \#an exemple \#of \_my\_ \* function

    options: [.regularExpression] 参数启用正则表达式搜索模式。

    [#*_] 模式匹配 #*_,然后每个匹配项都替换为反斜杠 (\\\\) 和匹配值 ($0)。请注意,替换字符串中的反斜杠必须加倍,因为反斜杠在替换模式中具有特殊含义(当 $ 前面带有反斜杠时,它可能用于使 $0 成为文字字符串)。

    【讨论】:

    • 完美!非常感谢!我试过了,但我没有写 4 个反斜杠,这就是为什么它不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多