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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With