如何使用正则表达式在iOS中获得匹配?
问题描述:
我得到了一个像'stackoverflow.html'字符串和正则表达式'堆栈(。).html'我想在(。)中的值。如何使用正则表达式在iOS中获得匹配?
我只能找到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,但我只对(。*)中的whats感兴趣。我想要“溢出”回来。在PHP中,这很容易实现,但是如何在xCode for iOS中实现这一点?
从逻辑上讲,如果我这样做:
NSInteger firstPartLength = 5;
NSInteger secondPartLength = 5;
NSLog (@"%@", [string substringWithRange:(NSRange){range.location + firstPartLength, range.length - (firstPartLength + secondPartLength)}]
它给我的PROPERT结果 '溢出'。但问题是在很多情况下我不知道第一部分或第二部分的长度。那么有没有一种方法可以获得应该在(。*)中的值?
或者我必须通过查找(。)的位置并从中计算第一部分和第二部分来决定选择最丑陋的方法吗?但是在正则表达式中,你可能也有([a-z]),但使用另一个正则表达式获取()之间的值的位置并使用它来计算左边和右边部分的丑恶方式?如果我有更多的事情会发生什么?像'A(。)应该找到答案(。*)。'我想有一个数组作为结果,值[0]是A后的值,[1]是后面的值。
我希望我的问题很清楚。
由于提前,
答
你想为了执行正则表达式的RegexKitLite库匹配:
http://regexkit.sourceforge.net/RegexKitLite/
之后,它几乎完全一样,你在PHP中做到这一点。
我会添加一些代码来帮助你吧:
NSString *string = @"stackoverflow.html";
NSString *expression = @"stack(.*)\\.html";
NSString *matchedString = [string stringByMatching:expression capture:1];
matchedString是@“溢出”,这应该是你所需要的东西。
答
中的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
我认为NSRegularExpression相比Perl或Ruby或许多其他语言更加有用 – SAKrisT 2011-11-06 17:54:57
,NSRegularExpression是强大的,但最常见的情况下使用了一段做一句话的价值。我喜欢这个库例子如何让你匹配一个表达式并在一个合理的线上捕获一个组。 – 2014-02-11 19:28:00