How do we get a substring from :

NSString *string = @"exmple string [image]";

where we want to extract the string in between "[" and "]".

I was thinking of using NSRange with:

NSRange rangeStart = [title rangeOfString:@"[" options:NSLiteralSearch];
NSRange rangeEnd = [title rangeOfString:@"]" options:NSLiteralSearch];

But i can't seem to find a solution on this.

有帮助吗?

解决方案

Variant 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)];

Variant 2:

NSArray *ar = componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[]"];
substring = ar[1];

其他提示

Take a look at NSRegularExpression and this answer will give you the regular expression you want.

Usage fo regular expression (Regex) is the way to go for this type of thing:

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