Swift 正则表达式替换每一新行的空格

Swift 正则表达式替换每一新行的空格,swift,regex,nsregularexpression,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: .caseInsensi

我正在将用户输入保存为一个字符串,并希望删除每行的所有空格

用户输入:

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")
让regex=试试看!NSRegularExpression(模式:“\n[\\s]+”,选项:。不区分大小写)
a=regex.stringByReplacingMatches(在:a中,选项:[],范围:NSRange(0..您可以使用

let regex = try! NSRegularExpression(pattern: "(?m)^\\h+", options: .caseInsensitive)
实际上,由于模式中没有大小写字符,您可以删除
.case-insensitive
,然后使用:

let regex = try! NSRegularExpression(pattern: "(?m)^\\h+", options: [])
请参见。该模式表示:

  • (?m)
    -打开多行模式
  • ^
    -由于
    (?m)
    ,它匹配任何线路起始位置
  • \h+
    -一个或多个水平空白
Swift代码示例:

let txt=“嗨!\n\n我的名字是:\n鲍勃\n\n我来自美国。”
let regex=“(?m)^\\h+”
打印(txt.replacingOccurrences(of:regex,with:,options:[.regularExpression]))
输出:

Hi!

My name is:
Bob

I am from the USA.

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

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"}