简体   繁体   中英

how to get sub string using regular expression

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM