0

How do you replace more than two occurrence of \r&\n into one in a String?

if the sample string is Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec blandit magna et quam maximus elementum et id ex.\r\n Donec luctus massa ut sapien consectetur blandit. Maecenas vehicula ex odio, eu sollicitudin felis vehicula sed. \nPhasellus hendrerit neque volutpat urna fermentum, eget cursus erat finibus. \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n

should not remove single or two occurrences.

Tried this code:

let regex = try! NSRegularExpression(pattern: "[\r\n]+", options: NSRegularExpression.Options.caseInsensitive)
let range = NSMakeRange(0, sampleString.count)
let modString = regex.stringByReplacingMatches(in: sampleString, options: [], range: range, withTemplate: "")
alpha47
  • 305
  • 3
  • 17

1 Answers1

4

In order to remove only from three to more occurrences you should change the matching pattern from [\r\n]+ to (\r\n){3,}.

So the above code should become

let regex = try! NSRegularExpression(pattern: "(\r\n){3,}", options: NSRegularExpression.Options.caseInsensitive)
let range = NSMakeRange(0, sampleString.count)
let modString = regex.stringByReplacingMatches(in: sampleString, options: [], range: range, withTemplate: "")
tx2
  • 724
  • 13
  • 26
  • logically it should work, but this also removes single occurrence – alpha47 Sep 01 '18 at 14:57
  • This removes 3 or more of any combination of \r or \n characters. The goal seems to be to remove 3 or more pairs of \r\n. Replace the `[` and `]` with `(` and `)`. – rmaddy Sep 01 '18 at 15:11
  • I have not understand this scenario at first. I've edited the response with that in mind. – tx2 Sep 01 '18 at 15:20