我有一个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\_ \* function
options: [.regularExpression]
参数启用正则表达式搜索模式。[#*_]
模式匹配#
,*
或_
,然后将每个匹配项替换为反斜杠(\\\\
)和匹配值($0
)。请注意,必须在替换字符串中将反斜杠加倍,因为反斜杠在替换模式中具有特殊含义(当$0
前面带有反斜杠时,可将其用作文字字符串)。
关于ios - 与Swift结合使用多个replaceOccurrences(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61060905/