how to get sub string using regular expression

85 views Asked by At

I am trying to get the substring which is The access token provided is invalid from

Access to the requested resource path is unauthorized: v1/streaming/video/558489e46b66d1023309e1a1 [The access token provided is invalid]

What I am doing is

  NSError *err = nil;
  NSRegularExpression *regex  =   [NSRegularExpression regularExpressionWithPattern:@"[(.*)]" options:0 error:&err];
  NSString *message = nil;

  if (regex) {
      NSTextCheckingResult *result = [regex firstMatchInString:(NSString*)error.userInfo[@"NSLocalizedDescription"]
                                                        options:0
                                                          range:NSMakeRange(0, ((NSString*)error.userInfo[@"NSLocalizedDescription"]).length)];

       if ( result ) {
           NSRange range = [result rangeAtIndex:1];
           message = [((NSString*)error.userInfo[@"NSLocalizedDescription"]) substringWithRange:range];

       }
   }

However message is nil. My idea is to pick up any words between [].I think there is something wrong with my regular since I am using [(.*)].

Does anyone have any hints on this issue.

1

There are 1 answers

0
zaph On

ICU User Guide: Regular Expressions

The regex: (?<= \\[)[^\\]]+(?=\\])

(?<= \\[) Look-behind assertion for [ which must be escaped
[^\\]]+ One or more characters not ] which must be escaped
(?=\\]) Look-ahead assertion for ] which must be escaped

NSString *string = @"Access to the requested resource path is unauthorized: v1/streaming/video/558489e46b66d1023309e1a1 [The access token provided is invalid]";
NSString *regex = @"(?<= \\[)[^\\]]+(?=\\])";
NSRange range = [string rangeOfString:regex options:NSRegularExpressionSearch];
NSLog(@"range: %@", NSStringFromRange(range));
NSLog(@"found: %@", [string substringWithRange:range]);

Output:

range: {100, 36}
found: The access token provided is invalid