5

我有以下 NSString:

Hello (my name is) John

如何(my name is)快速轻松地移除零件?我想确保它可以处理只有 a(然后是跟随)并且不会在其他任何东西上崩溃的情况。

4

3 回答 3

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}];

(重复过程直到有括号)

于 2013-06-04T20:01:39.397 回答
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 = @"\\(.*?\\)";
于 2013-06-04T20:27:28.800 回答
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;
}
于 2013-06-04T20:00:22.773 回答