swift - 正则表达式替换每行的空格

标签 swift regex nsregularexpression

我将用户输入保存到数据库作为字符串,并且我想删除每行的所有空格。

用户输入:

Hi!

My name is:
   Bob

I am from the USA.

我想删除“Bob”之间的空格,因此结果将是:

Hi!

My name is:
Bob

I am from the USA.

我正在尝试使用以下代码来做到这一点

let regex = try! NSRegularExpression(pattern: "\n[\\s]+", options: .caseInsensitive)
a = regex.stringByReplacingMatches(in: a, options: [], range: NSRange(0..<a.utf16.count), withTemplate: "\n")

但是这段代码替换了多个新行“\n”,我不想这样做。 运行上述代码后:“1\n\n\n 2” -> “1\n2”。我需要的结果:“1\n\n\n2”(仅删除空格,而不删除新行)。

最佳答案

无需正则表达式,将新行字符上的字符串拆分为数组,然后修剪所有行并再次将它们连接在一起

let trimmed = string.components(separatedBy: .newlines)
    .map { $0.trimmingCharacters(in: .whitespaces) }
    .joined(separator: "\n")

或者你可以使用reduce

let trimmed = string.components(separatedBy: .newlines)
    .reduce(into: "") { $0 += "\($1.trimmingCharacters(in: .whitespaces))\n"}
    

关于swift - 正则表达式替换每行的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64413981/

相关文章:

xcode - 使用 Swift Xcode 在 Mac 应用程序中运行终端命令

ios - 解码具有不同类型的 Json 对象

regex - XML 模式中正则表达式的正确语法

javascript - 当字符串包含方括号时正则表达式中断

ios - 文本中只允许 2 个空格

objective-c - 如何删除 "implicit conversion loses integer precision: ' NSInteger'(又名 'long')到 'int' 的 100 条警告“我在更新到 arm64 后收到?

ios - Swift/Backendless -Facebook 登录可在 iPhone 上使用,但不能在 iPad 模拟器上使用。如何正确使用Facebook SDK?

ios - 无法使用 '[APISKeyObjects]' 类型的索引为 'String' 类型的值添加下标吗?

java - 使用正则表达式制作 axception word 源代码

ios - 优化 NSRegularExpression 性能