如何使用正则表达式删除字符串中间的新行

Jac*_*erg 1 string trim ios swift

我想弄清楚如何\n用最多两个中断替换多个中断 ( )。我使用trimmingCharacters(in:)删除字符串周围的所有空格和新行,但我不知道如何删除字符串中的空格,或者说:我怎么能替换超过 2 个中断最多2次休息?

例如:

如果用户在 textView 中写入单词之间有空格,则字符串将为:

"Hello






I like coffee"
Run Code Online (Sandbox Code Playgroud)

我想实现的字符串结果:

"Hello

I like coffee"
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 5

您可以直接在 a 上进行正则表达式替换String

extension String {
    func trimString() -> String {
        return replacingOccurrences(of: "\\n{3,}", with: "\n\n", options: .regularExpression)
    }
}
Run Code Online (Sandbox Code Playgroud)

\n{3,}模式匹配三个或更多换行符。