我们如何从以下字符串获取子字符串:
NSString *string = @"exmple string [image]";
我们想要在“[”和“]”之间提取字符串。
我在考虑使用NSRange:
NSRange rangeStart = [title rangeOfString:@"[" options:NSLiteralSearch];
NSRange rangeEnd = [title rangeOfString:@"]" options:NSLiteralSearch];
但我似乎无法找到解决方案。
答案 0 :(得分:1)
变式1:
NSRange rangeStart = [title rangeOfString:@"[" options:NSLiteralSearch];
NSRange rangeEnd = [title rangeOfString:@"]" options:NSLiteralSearch];
substring = [your_string substringWithRange:NSMakeRange(rangeStart.location + 1, rangeEnd.location - rangeStart.location - 1)];
变式2:
NSArray *ar = componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[]"];
substring = ar[1];
答案 1 :(得分:0)
看看NSRegularExpression,this answer将为您提供所需的正则表达式。
答案 2 :(得分:0)
使用正则表达式(
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