开发者

Search for square brackets in NSString

开发者 https://www.devze.com 2023-03-26 17:35 出处:网络
I have some text loaded into NSString objects which contains annotations in square brackets - I need to strip the square brackets and everything within them so the user is only presented with the body

I have some text loaded into NSString objects which contains annotations in square brackets - I need to strip the square brackets and everything within them so the user is only presented with the body text.

However, because of the reliance of Objective-C on square brackets for messaging etc..., I'm having a bit of a problem removing them.

I开发者_如何学运维s there some special escape character for using square brackets (for example as an argument to 'rangeOfString:')? Xcode repeatedly informs me that there isn't.

Cheers


You can use regular expressions to remove substrings you want:

NSString *s = @"hi[bla]tototo[lalA123]a";
NSString *result = [s stringByReplacingOccurrencesOfString:@"\\[[\\w]+\\]" 
                                                withString:@""
                                                   options:NSRegularExpressionSearch|NSCaseInsensitiveSearch
                                                     range:NSMakeRange(0, [s length])];
NSLog(@"%@", result);
// output "hitototoa"

P.S. You may need to adjust regexp pattern if your annotations may contain characters that not match '\w' specifier


You mean like @"[" and @"]" ?

Any string in Objective-C must be between @" and ".


I think Vladimir's regex-based answer is fine, but I wanted to address the point about using rangeOfString because OP sounds very confused. There's no problem using square brackets inside NSStrings, and this has nothing to do with Objective C's use of square brackets for messaging.

This works fine for me:

NSString * a = @"Some [thing] here";
NSRange rangeOpen = [a rangeOfString:@"["];
NSRange rangeClose = [a rangeOfString:@"]"];
NSLog(@"%lu %lu, %lu %lu.",
      (unsigned long)rangeOpen.location,
      (unsigned long)rangeOpen.length,
      (unsigned long)rangeClose.location,
      (unsigned long)rangeClose.length);
# Logs "5 1, 11 1."
0

精彩评论

暂无评论...
验证码 换一张
取 消