如何用正则表达式替换字符并保留符号?

问题描述 投票:0回答:1

我需要添加反斜杠(转义)所有特殊符号,例如

(,),+,[,]
示例:

extension String {
    var escaping: String {
        return self.replacing(/[()+]/, with: "\\($0)")
    }
}

let text = "Hello everyone!)) + another one day"
print(text.escaping)

所以我需要得到结果:

"Hello everyone!\)\) \+ another one day"

有什么办法可以用 swift 中的正则表达式来做到这一点吗?不使用

replacingOccurrences(of

var escaping: String {
        return self.replacingOccurrences(of: ".", with: "\\.")
            .replacingOccurrences(of: "-", with: "\\-")
            .replacingOccurrences(of: "_", with: "\\_")
            .replacingOccurrences(of: ")", with: "\\)")
            .replacingOccurrences(of: "(", with: "\\(")
            .replacingOccurrences(of: "(", with: "\\(")
            .replacingOccurrences(of: "+", with: "\\+")
            .replacingOccurrences(of: "!", with: "\\!")
            .replacingOccurrences(of: "[", with: "\\[")
            .replacingOccurrences(of: "]", with: "\\]")
            .replacingOccurrences(of: "=", with: "\\=")
            .replacingOccurrences(of: "|", with: "\\|")
            .replacingOccurrences(of: "{", with: "\\{")
            .replacingOccurrences(of: "}", with: "\\}")
    }

相关:Telegram 不会转义某些 Markdown 字符

swift
1个回答
0
投票

您可以使用带有闭包replacing

(Regex<Output>.Match) -> Replacement
重载来访问匹配结果,这样您就可以使用匹配结果作为替换的一部分。

extension String {
    var escaping: String {
        self.replacing(/[()+.\-_!\[\]=|{}]/) { match in "\\" + match.output }
    }
}

请注意,您应该在角色类中转义

-
[
]

还可以考虑将

\
放入角色类中。你肯定也想逃避这个(?)

© www.soinside.com 2019 - 2024. All rights reserved.