2

I am saving users input to db as a string and I would like to remove all spaces at each lines.

Input from user:

Hi!

My name is:
   Bob

I am from the USA.

I want to remove spaces between "Bob", so the result will be:

Hi!

My name is:
Bob

I am from the USA.

I am trying to do it with the following code

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

but this code replace multiple new lines "\n", I don't want to do it. After I run the above code: "1\n\n\n 2" -> "1\n2". The result I need: "1\n\n\n2" (only spaces are removed, not new lines).

2 Answers2

2

No need for regex, split the string on the new line character into an array and then trim all lines and join them together again

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

or you can use reduce

let trimmed = string.components(separatedBy: .newlines)
    .reduce(into: "") { $0 += "\($1.trimmingCharacters(in: .whitespaces))\n"}
    
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
1

You can use

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

Actually, as there are no case chars in the pattern, you may remove .caseInsensitive and use:

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

See the regex demo. The pattern means:

  • (?m) - turn on multiline mode
  • ^ - due to (?m), it matches any line start position
  • \h+ - one or more horizontal whitespaces.

Swift code example:

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]) )

Output:

Hi!

My name is:
Bob

I am from the USA.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563