0

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.

Frank
  • 3,073
  • 5
  • 40
  • 67

3 Answers3

1

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];
Avt
  • 16,927
  • 4
  • 52
  • 72
0

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

Community
  • 1
  • 1
brindy
  • 4,585
  • 2
  • 24
  • 27
0

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
tiguero
  • 11,477
  • 5
  • 43
  • 61