2013-03-15 107 views
0

我有一個NSString我想用NSRegularExpression進行測試,但它不會像我期望的那樣執行任何操作,而且我也不知道在哪裏搜索答案。「 P {Letter}」和NSRegularExpression

因此,這裏是我的代碼:

BOOL companyNameContainsOnlyAuthorizedCharacters = YES; 

    NSError *error = nil; 
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[\P{Letter}]" options:0 error:&error]; 
    NSArray *matches = [[NSArray alloc] init]; 
    matches = [regex matchesInString:[model editorName] options:0 range:NSMakeRange(0,[[model editorName] length])]; 

    if ([matches count] > 0) { 

     companyNameContainsOnlyAuthorizedCharacters = NO; 

    } 

對於我所知道的,[\ p {}信]應匹配什麼,但信件。儘管如此,它只是匹配字符「\」,「P」,「{」,「L」,「e」,「t」,「r」和「}」。我也嘗試了沒有括號[],但它根本不匹配任何東西。

任何幫助將不勝感激,提前謝謝。

編輯: 此外,Xcode中給了我一個警告\ P是一個未知的轉義序列...

+0

你想要什麼? – Balu 2013-03-15 10:24:43

+0

我想知道我做錯了什麼。 – user2006934 2013-03-15 10:25:45

+0

你想給A到Z的字母吧? – Balu 2013-03-15 10:29:24

回答

0

您需要兩個反斜槓:

regularExpressionWithPattern:@"[\\P{Letter}]" 

因爲反斜槓本身需要進行轉義一個字符串。

一個可能被簡單的解決方案,以檢查「字母只有」是

NSString *stringToTest = ...; 
NSCharacterSet *letterCharset = [NSCharacterSet letterCharacterSet]; 
BOOL lettersOnly = [[stringToTest stringByTrimmingCharactersInSet:letterCharset] length] == 0; 
+0

好的,這個工程。非常感謝你:) – user2006934 2013-03-15 10:39:42

+0

@ user2006934:不客氣。我已經爲答案添加了一個替代解決方案,可能它很有用。 – 2013-03-15 10:56:58

0

你需要兩個反斜槓。另外,您不需要將其放在模式括號中。

regularExpressionWithPattern:@"\\P{Letter}" 
+0

謝謝。有用 :) – user2006934 2013-03-15 10:40:20