Replace only one occurrence of \ n or \ r in NSString

I am reading text from PDF to NSString. I am replacing all spaces using below code

NSString *pdfString = convertPDF(path);
    pdfString=[pdfString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    pdfString=[pdfString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    pdfString=[pdfString stringByReplacingOccurrencesOfString:@"\n" withString:@""];

      

But it also removes paragraph spaces and multiple lines. I want to replace only one occurrence of \ n or \ r and keep paragraph spaces or multiple tabs and next lines.

+3


source to share


3 answers


There are two approaches:

  • Do a manual search in a loop

You can get the range of a string with -rangeOfCharactersFromSet:options:range:

. The pearl of this approach is to reduce the search range with each match it finds. With this, you can simply compare the found range with the search range. If the range found is at the very beginning, it was double (or triplex) \r

.



  1. Get individual components

C -componentsSeparatedByCharactersFromSet:

( NSString

) returns an array with strings separated \r

. Empty lines in this array are double (or triple) \r

. Just replace them with \r

and then attach the components to the blank.

+3


source


You have to use NSRegularExpression to do this



NSString *pdfString = convertPDF(path);

//Replace all occurrences of \n by a single \n
NSRegularExpression *regexN = [NSRegularExpression regularExpressionWithPattern:@"\n" options:0 error:NULL];
pdfString = [regexN stringByReplacingMatchesInString:pdfString options:0 range:NSMakeRange(0, [pdfString length]) withTemplate:@"\n"];

//Replace all occurrences of \r by a single \r
NSRegularExpression *regexR = [NSRegularExpression regularExpressionWithPattern:@"\r" options:0 error:NULL];
pdfString = [regexR stringByReplacingMatchesInString:pdfString options:0 range:NSMakeRange(0, [pdfString length]) withTemplate:@"\r"];

      

+1


source


Have you tried regex? You can only catch occurrences where \n

one appears without the other \n

, and then replace those occurrences with an empty string:

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\n]([\n])[^\n];" options:0 error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];

      

0


source







All Articles