2010-11-15 82 views
25

我得到了一個像'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]是後面的值。

我希望我的問題很清楚。

由於提前,

回答

1

你想爲了執行正則表達式的RegexKitLite庫匹配:

http://regexkit.sourceforge.net/RegexKitLite/

之後,它幾乎完全一樣,你在PHP中做到這一點。

我會添加一些代碼來幫助你吧:

NSString *string  = @"stackoverflow.html"; 
NSString *expression = @"stack(.*)\\.html"; 
NSString *matchedString = [string stringByMatching:expression capture:1]; 

matchedString是@「溢出」,這應該是你所需要的東西。

+3

我認爲NSRegularExpression相比Perl或Ruby或許多其他語言更加有用 – SAKrisT 2011-11-06 17:54:57

+0

,NSRegularExpression是強大的,但最常見的情況下使用了一段做一句話的價值。我喜歡這個庫例子如何讓你匹配一個表達式並在一個合理的線上捕獲一個組。 – 2014-02-11 19:28:00

91

中的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