Ganesh Guturi Ganesh Guturi - 2 months ago 11
iOS Question

How to remove sequence of characters from NSString

I have a string which contains characters and I need to find out a shortest string or remove sequence of characters from that string.

Eg: NSString *string = @"FIRSTEXAMPLEEXAMPLETEST";
Output: FIRSTEXAMPLETEST


Can you please help me on finding a suitable
Regex format
to achieve it. Thanks in advance.

Answer

You may use (.+)\1+ regex that will match the longest consecutive substrings and replace with their single occurrences using the 1st backreference $1.

Use

NSError *error = nil;
NSString *string = @"FIRSTEXAMPLEEXAMPLETEST";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(.+)\\1+" options:nil error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@"$1"];
NSLog(@"%@", modifiedString); // => FIRSTEXAMPLETEST

See Objective-C demo

Pattern details:

  • (.+) - Group 1 capturing one or more characters other than newline (use (?s) flag before to allow matching newlines with the dot)
  • \1+ - one or more occurrences of the same substrings captured in Group 1.