如何使用正则表达式获取子字符串

时间:2015-06-25 01:44:32

标签: ios objective-c iphone nsregularexpression

我正在尝试从

获取Call: lm(formula = y ~ x1 + x2 + x3 + z1 + z2 + z3, data = df) Residuals: Min 1Q Median 3Q Max -2.76472 -0.56958 -0.02673 0.50188 2.61362 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 0.18092 0.09966 1.815 0.0727 . x1 0.12282 0.10231 1.201 0.2330 x2 -0.22411 0.10781 -2.079 0.0404 * x3 -0.01096 0.09554 -0.115 0.9090 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.9596 on 93 degrees of freedom Multiple R-squared: 0.07717, Adjusted R-squared: 0.01763 F-statistic: 1.296 on 6 and 93 DF, p-value: 0.2667 的子字符串
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之间找到任何单词。我认为我的常规有问题,因为我使用[]

有没有人对这个问题有任何暗示。

1 个答案:

答案 0 :(得分:0)

ICU用户指南:Regular Expressions

正则表达式:(?<= \\[)[^\\]]+(?=\\])

(?<= \\[)后视断言[必须逃脱的 [^\\]]+一个或多个必须转义的字符 (?=\\])前瞻性断言,必须转义

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}
  found:提供的访问令牌无效