【问题标题】:Regex replace spaces at each new lines正则表达式在每个新行替换空格
【发布时间】:2021-02-01 10:35:11
【问题描述】:

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

用户输入:

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"(只删除空格,不删除新行)。

【问题讨论】:

    标签: swift regex nsregularexpression


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你可以使用

      let regex = try! NSRegularExpression(pattern: "(?m)^\\h+", options: .caseInsensitive)
      

      实际上,由于模式中没有大小写字符,您可以删除 .caseInsensitive 并使用:

      let regex = try! NSRegularExpression(pattern: "(?m)^\\h+", options: [])
      

      请参阅regex demo。图案的意思是:

      • (?m) - 开启多行模式
      • ^ - 由于(?m),它匹配任何行开始位置
      • \h+ - 一个或多个水平空格。

      Swift 代码示例:

      let txt = "Hi!\n\nMy name is:\n   Bob\n\nI am from the USA."
      let regex = "(?m)^\\h+"
      print( txt.replacingOccurrences(of: regex, with: "", options: [.regularExpression]) )
      

      输出:

      Hi!
      
      My name is:
      Bob
      
      I am from the USA.
      

      【讨论】:

        猜你喜欢
        • 2013-01-10
        • 1970-01-01
        • 2012-06-18
        • 2020-09-12
        • 1970-01-01
        • 1970-01-01
        • 2021-07-04
        • 2015-09-16
        • 1970-01-01
        相关资源
        最近更新 更多