ios - 与Swift结合使用多个replaceOccurrences()

标签 ios swift regex string swift5

我有一个String,我想向特定字符添加反斜杠,因为我使用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 
}

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

最佳答案

您可以使用

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

使用原始字符串文字:
var modString = myString.replacingOccurrences(of: "[#*_]", with: #"\\$0"#, options: [.regularExpression])

结果:This is \#an exemple \#of \_my\_ \* functionoptions: [.regularExpression]参数启用正则表达式搜索模式。
[#*_]模式匹配#*_,然后将每个匹配项替换为反斜杠(\\\\)和匹配值($0)。请注意,必须在替换字符串中将反斜杠加倍,因为反斜杠在替换模式中具有特殊含义(当$0前面带有反斜杠时,可将其用作文字字符串)。

关于ios - 与Swift结合使用多个replaceOccurrences(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61060905/

相关文章:

objective-c - 从 iOS 应用程序向 Facebook 发布状态更新

ios - 自定义按钮view : detect touch down/up, 快速回退拖拽到UIScrollView

javascript - 用一个替换多个连续的连字符

java - 模式名称特殊字符

ios - 如何获取用户位置

ios - 全新安装的核心数据迁移

ios - NSURL 可能不响应警告 +encryptedFileWithPath

Swift 如何将 `struct` 的默认初始值设定项设为私有(private)

ios - 使用 Firebase 创建用户时,用户变量为 nil

php - 每个正则表达式模式的 laravel 自定义验证错误