1

I am trying to figure out how to replace multiple breaks (\n) with a maximum breaks of two. I used trimmingCharacters(in:) to remove all the white spaces and new lines around the string, but I can't figure out how to remove the space within the string, or rather said: how could I replace more than 2 breaks to be maximum of 2 breaks?

For an instance:

If the user writes in a textView with spaces between the words, the string will be:

"Hello






I like coffee"

The string result I'd like to achieve:

"Hello

I like coffee"
Jacob Ahlberg
  • 1,560
  • 4
  • 14
  • 34

2 Answers2

5

You can do a regular expression replacement directly on a String:

extension String {
    func trimString() -> String {
        return replacingOccurrences(of: "\\n{3,}", with: "\n\n", options: .regularExpression)
    }
}

The \n{3,} pattern matches three or more newline characters.

Martin R
  • 488,667
  • 78
  • 1,132
  • 1,248
  • The solution is perfect but if there is a space and then a new line will not remove it I better use this `(?:[\\t ]*(?:\\r?\\n|\\r))+` this is your expression https://regex101.com/r/1PiFam/1 , this is my expression https://regex101.com/r/Cwosbp/1 – a.masri May 04 '18 at 13:00
0

I solved this by using a regular expression of: \n{2,500} and replaced all with "\n\n".

It's working perfectly!

extension String {
    func trimString() -> String {
        let pattern = "\n{2,500}"
        let regex = try! NSRegularExpression(pattern: pattern, options: .dotMatchesLineSeparators)
        let range = NSMakeRange(0, self.count)
        let trimmedString = regex.stringByReplacingMatches(in: self, options: .reportProgress, range: range, withTemplate: "\n\n")
        return trimmedString
    }
}
Jacob Ahlberg
  • 1,560
  • 4
  • 14
  • 34
  • Using `self.count` for computing the NSRange is not correct – try it with `"\n\n\nx"`. (Explanation here https://stackoverflow.com/a/27880748/1187415 :) – Martin R May 04 '18 at 12:47
  • I tried to change it to something else and it didn't worked. I'm using the `self.count` to grab the length of the string. I checked out your link and I saw `NSMakeRange(0, nsString.length)`. Could you tell me what the difference is? By the way, I love your answer! @MartinR – Jacob Ahlberg May 04 '18 at 12:53
  • 1
    NSRange is related to NSString and counts UTF-16 code units. `self.utf16.count` would also make it work. – Martin R May 04 '18 at 12:54