用法FO正则表达式(正则表达式)是去这种类型的事情的方式:
NSError* error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[(.*?)\\]" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *str = @"example string [image]";
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
NSString *substringForFirstMatch;
if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
substringForFirstMatch = [str substringWithRange:NSMakeRange(rangeOfFirstMatch.location + 1, rangeOfFirstMatch.length - 2)];
}
NSLog(@"%@", substringForFirstMatch); // will print image
这是正确的开始。使用这两个范围的结果来获取子字符串。 – rmaddy