我正在尝试从可能以任何模式出现的字符串中删除多个换行符/回车符(这些字符串来自社交网络 API - TW、FB、YT)。我能够删除几乎所有组合,但我似乎无法删除“\r\n”或“\n\r”的多次重复。
我想要的是: "Line1\r\nLine2\n\n\n\n\n\n\n\nLine3\r\r\r\r\rLine4\r\n\"Line5\"\ n\r\n\rLine6\rLine7\r\n\r\nLine8\r\r\r\r\r\r\r\n\n\n\rLine9\n\n\n\n\ n\r\r\r\r\nLine10\nLine11\n\n\n\n"
变得:
Line1
Line2
Line3
Line4
"Line5"
Line6
Line7
Line8
Line9
Line10
Line11
但目前我得到:
Line1
Line2
Line3
Line4
"Line5"
Line6
Line7
Line8
Line9
Line10
Line11
这是我的代码:
NSMutableString *testString = [[NSMutableString alloc]init];
[testString appendString:@"Line1\r\nLine2\n\n\n\n\n\n\n\nLine3\r\r\r\r\rLine4\r\n\"Line5\"\n\r\n\rLine6\rLine7\r\n\r\nLine8\r\r\r\r\r\r\r\r\n\n\n\rLine9\n\n\n\n\n\r\r\r\r\nLine10\nLine11\n\n\n\n"];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\r+)(\\n+)?(\r+)?|(\\n+)(\r+)?(\\n+)?|(\\n\r+)|(\r\\n+)" options:NSRegularExpressionCaseInsensitive error:nil];
[regex replaceMatchesInString:testString options:0 range:NSMakeRange(0, [testString length]) withTemplate:@"\n"];