簡體   English   中英

如何使用正則表達式獲取子字符串

[英]how to get sub string using regular expression

我正在嘗試獲取以下子字符串,即The access token provided is invalid

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

我在做什么

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

       }
   }

但是message為零。 我的想法是拾起[]之間的任何單詞。由於我正在使用[(.*)] ,因此我的常規單詞有誤。

有沒有人對此問題有任何提示。

ICU用戶指南: 正則表達式

正則表達式: (?<= \\\\[)[^\\\\]]+(?=\\\\])

(?<= \\\\[) [必須轉義的后置斷言
[^\\\\]]+一個或多個不是]的字符必須轉義
(?=\\\\])必須轉義的]的預先聲明

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

輸出:

范圍:{100,36}
找到:提供的訪問令牌無效

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM