0

I have a following string in iOS :-

[{"status":"0","eventid":"126"}]15.511563,73.809732[{"status":"0"}]

And I am trying to fetch this :-

[{"status":"0","eventid":"126"}]

i.e. the entire portion of string before first ] closing bracket.

I tried this in which I get a substring of 31 characters, but this won't work if the contents between the brackets changes.

NSRange start = [result1 rangeOfString:@"["];

NSString *shortString =[result1 substringWithRange:NSMakeRange(start.location, 31)];

result1 = [result1 substringToIndex:shortString.length];
NSLog(@"Response- %@",result1);

What is the correct approach?

1
  • if you are getting [{"status":"0","eventid":"126"}]15.511563,73.809732[{"status":"0"}] from server tell them to make it as ({"status":"0","eventid":"126"}]15.511563,73.809732[{"status":"0"}) because "(" ")" refers array.. Commented Mar 12, 2014 at 12:49

3 Answers 3

1

Just like you are getting the start range (NSRange start = [result1 rangeOfString:@"["];), also get the end range:

NSRange end = [result1 rangeOfString:@"]"];

Now you have enough information to extract the substring:

NSString *result = [result1 substringWithRange:NSMakeRange(start.location, end.location - start.location)];

In your current code, you don't need to use substring... methods twice as you have already extracted the string you want in the first call. Making the second call is just ignoring the bit of code which found the start location and assuming that you always want the substring from the start of the string, which is less flexible.

Sign up to request clarification or add additional context in comments.

Comments

1

Make the END Range also

NSRange start;
NSRange end;
start = [result1 rangeOfString: @"["];
end = [result1 rangeOfString: @"]"];

NSString *newResult = [result1 substringWithRange:NSMakeRange(start.location+1, end.location)];

NSLog(@"%@", newResult);

Comments

0

You could try using a NSRegularExpression:

NSError *error = NULL;
NSRegularExpression *regex =
    [NSRegularExpression regularExpressionWithPattern:@"\\[(.*?)\\]"
         options:NSRegularExpressionCaseInsensitive
           error:&error];

Now, search for the first match:

NSString *string = @"[{\"status\":\"0\",\"eventid\":\"126\"}]15.511563,73.809732[{\"status\":\"0\"}]";
NSTextCheckingResult *match =
    [regex firstMatchInString:string
                      options:0
                        range:NSMakeRange(0, [string length])];

Now you can get the range for the capture group:

NSRange block = [match rangeAtIndex:1];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.