Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove sequence of characters from NSString

Tags:

regex

ios

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.

like image 539
Ganesh G Avatar asked Nov 25 '25 17:11

Ganesh G


1 Answers

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.
like image 121
Wiktor Stribiżew Avatar answered Nov 27 '25 14:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!