首页 > 解决方案 > 将多个 replaceOccurrences() 与 Swift 结合使用

问题描述

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

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

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 
}

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

标签: iosswiftregexstringswift5

解决方案


您可以使用

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文字字符串)。$


推荐阅读