Ganesh Guturi Ganesh Guturi - 11 months ago 48
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.


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

Answer Source

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


NSError *error = nil;
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.