我将用户输入保存到数据库作为字符串,并且我想删除每行的所有空格。
用户输入:
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/