Reputation: 173
I'm trying to remove multiple newlines/carriage-returns from a string that may appear in any pattern (the strings come from social network APIs - TW, FB, YT). I was able to remove almost all combinations however I can't seem to remove multiple repetitions of "\r\n" or "\n\r".
What I would like is to have: "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"
become:
Line1
Line2
Line3
Line4
"Line5"
Line6
Line7
Line8
Line9
Line10
Line11
but currently I get:
Line1
Line2
Line3
Line4
"Line5"
Line6
Line7
Line8
Line9
Line10
Line11
This is the code I have:
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"];
Upvotes: 2
Views: 2557
Reputation: 33421
I tried this out on a regex validation site and it works -> (\\r|\\n)+
or if you don't need to capture (?:\\r|\\n)+
Well it will be a varying number of slashes depending on whether or not they are actual carriage returns or just \r and \n (Plus you need to double the number of slashes for putting them inside an NSString
literal)
Upvotes: 2