我有一个类似'stackoverflow.html'的字符串,并且在正则表达式'stack(.)。html'中我想要在(.)中包含该值。

我只能找到NSPredicate像:

NSString    *string     = @"stackoverflow.html";
NSString    *expression = @"stack(.*).html";
NSPredicate *predicate  = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", expression];
BOOL match = [predicate evaluateWithObject:string]

但这只能告诉我,当我使用NSRegularExpression时,有一个匹配项,并且不返回任何字符串:
NSRange range = [string rangeOfString:expression options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location == NSNotFound) return nil;

NSLog (@"%@", [string substringWithRange:(NSRange){range.location, range.length}]);

它将给我返回的总字符串为stackoverflow.html,但我只对(。*)中的内容感兴趣。我想让“溢出”回来。在PHP中这很容易做到,但是如何在iOS的xCode中完成呢?

逻辑上,如果我这样做:
NSInteger firstPartLength  = 5;
NSInteger secondPartLength = 5;
NSLog (@"%@", [string substringWithRange:(NSRange){range.location + firstPartLength, range.length - (firstPartLength + secondPartLength)}]

它给了我正确的结果“溢出”。但是问题是,在许多情况下,我不知道第一部分或第二部分的长度。那么有什么方法可以获取应该在(。*)中的值?

还是我必须决定通过找到(.)的位置来选择最丑陋的方法,然后从那里计算出第一部分和第二部分?但是,在正则表达式中,您可能也有([a-z]),但是使用另一个正则表达式获取()之间的值的位置然后再利用它来计算左右部分的丑陋方式呢?如果我还有更多呢?例如“(.)应该找到(。*)的答案。”我想要一个数组,其结果为[0] A之后的值和[1] to之后的值。

希望我的问题清楚。

提前致谢,

最佳答案

在iOS 4.0以上版本中,您可以使用NSRegularExpression:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"stack(.*).html" options:0 error:NULL];
NSString *str = @"stackoverflow.html";
NSTextCheckingResult *match = [regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
// [match rangeAtIndex:1] gives the range of the group in parentheses
// [str substringWithRange:[match rangeAtIndex:1]] gives the first captured group in this example

10-05 20:24
查看更多