[英]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. 能帮我找到合适的
Regex format
来实现它。 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
. 您可以使用
(.+)\\1+
正则表达式匹配最长的连续子字符串,并使用第一个反向引用$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 请参阅Objective-C演示
Pattern details : 图案细节 :
(.+)
- Group 1 capturing one or more characters other than newline (use (?s)
flag before to allow matching newlines with the dot) (.+)
- 第1组捕获除换行符之外的一个或多个字符(使用(?s)
标志之前允许匹配换行符与点) \\1+
- one or more occurrences of the same substrings captured in Group 1. \\1+
- 在第1组中捕获的相同子串的一次或多次出现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.