2011-11-06 69 views
0

我想驗證一個字符串,表示地名。我匹配一個簡單的字符集,這樣NSPredicate與正則表達式匹配國際字母字符集

NSString *regexName = @"[a-zA-Z][., a-zA-Z\\t\\-]*" 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexName]; 

我想知道簡單的正則表達式用來匹配更廣泛的國際字符集(主要是西方字符)。我可以列舉在正則表達式中可以想到的每個角色,但我想有另一種方法。我正在尋找想法。

回答

0

NSRegularExpression基於ICU正則表達式,並在其docs中列出了不少選項。

您正在尋找的那個是Letter屬性,編碼爲\p{Letter}(或簡稱\p{L})。

這裏是人誰願意看到它在實踐中的一些代碼:

NSArray *strings = [NSArray arrayWithObjects: 
          @"Joe", 
          @"Chloë", 
          @"Søren", 
          @"Renée", 
          @"Se7en", 
          @"Zürich", 
          @"Genève", 
          @"Tromsø", 
          @"Jane", 
          nil]; 

NSString *regexName = @"\\p{Letter}[., \\p{Letter}\\t\\-]*"; 

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexName]; 

NSArray *filteredArray = [strings filteredArrayUsingPredicate:predicate]; 

這一切都與字母的名稱匹配,而不是字符串「七宗罪」。

這個問題提到了西方字符,但它也會很好用來自使用其他字母的語言的例子。