ios - 将多个 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
}
我只想有一个适用于多个字符的“替换事件”。我想我可以用正则表达式做到这一点,但我不知道怎么做。如果您有想法,请与我分享。
解决方案
您可以使用
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
文字字符串)。$
推荐阅读
- django - 如何在实例化期间获取 CharField() 的值?
- jquery - 具有动态时隙的日期时间选择器
- javascript - 从本地(Angular)的响应标头中删除 Content-Security-Policy
- php - PHP `glob()` 多个前缀
- python - 无法读取图像特征 - Python 路径错误
- c - 如何在我自己的操作系统中从裸 C(无库)读取/写入软盘驱动器或 ATA 驱动器?
- c++ - 在 C++ 中重新定义 C 函数
- python - pd.to_datetime 产生“仅对唯一值索引对象有效的重新索引”
- aspnetboilerplate - AspNetBoilerplate Core MVC 自定义登录提供程序
- jsf - 有没有办法播放带有视频 xhtml 标签的 Java InputStream 或包含带有视频 xhtml 标签的授权标头?