如何删除NSString中包含括号()的子字符串?

时间:2013-06-04 19:52:15

标签: ios objective-c cocoa-touch nsstring nsrange

我有以下NSString:

Hello (my name is) John

如何快速轻松地删除(my name is)部分?我想确保它处理只有(然后跟随)并且不会在其他任何事情上崩溃的情况。

3 个答案:

答案 0 :(得分:8)

如果你想删除括号中的文字,那么......好吧,在括号之间删除文字。

NSMutableString *s = [NSMutableString stringWithString:@"Hello (my name is) John"];
NSRange start = [s rangeOfString:@"("];
NSRange end = [s rangeOfString:@")"];
[s deleteCharactersInRange:(NSRange){ start.location, end.location - start.location + 1}];

(重复过程,直到有parens)

答案 1 :(得分:6)

使用正则表达式(贪婪)很容易:

NSError *error = NULL;
NSString *stringToBeReplaced = @"Hello (my name is) John";
NSString *regexString = @"\\(.*\\)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:stringToBeReplaced options:0 range:NSMakeRange(0, [stringToBeReplaced length]) withTemplate:@""];
// Greedy means it will match "My name (is John) (Jobs)." => "My name ."

对于非贪婪的正则表达式,请使用:

NSString *regex = @"\\(.*?\\)";

答案 2 :(得分:0)

如果您的文字不止一次出现(),您可以尝试以下内容:

-(NSString *)clearString:(NSString *)stringToClear {
     while([stringToClear rangeOfString:@"("].location != NSNotFound) {
          NSRange firstRange = [stringToClear rangeOfString:@"("];
          NSRange secondRange = [stringToClear rangeOfString:@")"];
          stringToClear = [stringToClear stringByReplacingCharactersInRange:
                                 NSMakeRange(firstRange.location, secondRange.location)
                        withString:@""];
     }
     return  stringToClear;
}