2013-06-01 100 views
0

我試圖過濾字符串數組與此斷言:NSPredicate搜索LIKE

[NSPredicate predicateWithFormat:@"SELF LIKE[c] '#*!%d'", aNumber] 

每串這就好比#WILDCARD ANY_NUMBER是有效的!

但它不工作:( 你能幫我

編輯:?!

NSString *pattern = [@"#*!" stringByAppendingFormat:@"%d", numberVariable]; 
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern]; 
NSArray *filteredArray = [anArray filteredArrayUsingPredicate:pred]; 

數組anArray包含諸如#0字符串-1(numberVariable是-1),但陣列filterdArray是空的,所以正則表達式不起作用

編輯:。

我的解決方案:

「!#ANY_CHARACTERS ANY_NUMBER」
NSString *pattern = [@"#.*!\\" stringByAppendingFormat:@"%d", numberVariable]; 
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern]; 
NSArray *filteredArray = [anArray filteredArrayUsingPredicate:pred]; 
+0

您使用'%如果'aNumber'屬於'int'類型,那麼'd''什麼是#*? – CainaSouza

+0

如果你的描述說你想匹配任何數字,那麼'aNumber'是什麼 – Wain

回答

5

要找到像所有字符串與任意數量,你需要「匹配」運營商正則表達式:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"#.*!\\d+"]; 
NSArray *filtered = [yourArray filteredArrayUsingPredicate:pred]; 

如果你有一個具體的數字aNumber,並希望找到形式爲 的所有字符串「#ANY_CHARACTERS! < aNumber的>」,那麼下面應該工作:

NSString *pattern = [@"#*!" stringByAppendingFormat:@"%d", aNumber]; 
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF LIKE %@", pattern]; 
NSArray *filtered = [yourArray filteredArrayUsingPredicate:pred]; 

[NSPredicate predicateWithFormat:@"SELF LIKE[c] '#*!%d'", aNumber] 

的問題是,%d引號內不受aNumber取代

+0

謝謝..但這不起作用: - /我用我的新代碼編輯帖子..任何想法? – Maik639

+0

@ Maik639:你沒有完全複製我的第二個代碼示例,在這種情況下,它應該是「自己喜歡」而不是「自我匹配」。 –

+0

好的..你的更新後的文章幫了我很多。我用我的解決方案更新了這篇文章。謝謝! – Maik639