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.
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;
}
© 2022 - 2024 — McMap. All rights reserved.
(
and)
characters and remove everything in between (hey, this is just really is what you asked). – Bilbrey