I have the following NSString:

Hello (my name is) John

How do I remove the (my name is) part quickly and easily? I want to make sure it handles situations where there is only a ( and then a following ) and doesn't crash on anything else.

有帮助吗?

解决方案

If you want to remove text between parentheses, then... well, remove text between parentheses.

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

(repeat process until there are parens)

其他提示

Easy to do using regular expressions (greedy):

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 ."

For a non-greedy regular expression use:

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

If your text has more than one occurrence of () you could try something like:

-(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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top