2014-10-30 39 views
0

嗨,我有問題,如果在字符串中沒有電話號碼和NSRegularExpression找不到任何應用程序崩潰,但是當它確實找到它的電話號碼在字符串中的工作正常沒有問題。我怎樣才能阻止它崩潰。NSRegularExpression工作不正常

NSRegularExpression *phoneexpression = [NSRegularExpression regularExpressionWithPattern:@"\\d{4}-\\d{4}"options:NSRegularExpressionCaseInsensitive error:NULL]; 
NSString *phString = TextString; 
NSString *PH = [phString substringWithRange:[phoneexpression rangeOfFirstMatchInString:phString options:NSMatchingCompleted range:NSMakeRange(0, [phString length])]]; 

我覺得這是問題

NSString *PH = [phString substringWithRange:[phoneexpression rangeOfFirstMatchInString:phString options:NSMatchingCompleted range:NSMakeRange(0, [phString length])]]; 
+0

您是否嘗試將'NULL'更改爲'&error'?請顯示錯誤信息。 – 2014-10-30 10:22:56

回答

0

我猜你得到一個NSRangeException。

試試這樣說:

NSString *PH = nil; 
NSRegularExpression *phoneexpression = [NSRegularExpression regularExpressionWithPattern:@"\\d{4}-\\d{4}"options:NSRegularExpressionCaseInsensitive error:NULL]; 
NSString *phString = TextString; 
NSRange rg = [phoneexpression rangeOfFirstMatchInString:phString options:NSMatchingCompleted range:NSMakeRange(0, [phString length])]; 

if(rg.location != NSNotFound) 
    PH = [phString substringWithRange:rg]; 

它,你將它傳遞給substringWithRange前檢查返回的範圍是很重要的。 更多信息請參見本參考:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/#//apple_ref/occ/instm/NSString/substringWithRange

編輯: 還要檢查從rangeOfFirstMatchInString返回的範圍並不違反在參考記錄的邊界限制:

引發一個NSRangeException如果( aRange.location - 1)(aRange.location + aRange.length - 1)位於 接收器的末尾。