如何将多于两次的\r
&\n
替换为字符串中的一个?
如果示例字符串是
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
不应删除一次或两次。
对此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: "")
答案 0 :(得分:4)
要仅从三个事件中删除事件,应将匹配模式从[\r\n]+
更改为(\r\n){3,}
。
所以上面的代码应该变成
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: "")