2011-04-09 270 views
0

我想刪除字符串的特定部分,到目前爲止,我決定使用RegEx來匹配我想要刪除的字符串部分,但之後我不知道如何從該字符串中刪除特定的範圍原始字符串...如何使用NSRegularExpression從字符串中刪除子字符串?

我正在嘗試將333-333 Anywhere Lane更改爲333 Anywhere Lane。基本上我試圖刪除連字符後的任何其他數字。

這裏是我的代碼:

address = @"333-333 Anywhere Lane"; 

NSError *error = NULL; 

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"-[0-9]*" options:NSRegularExpressionCaseInsensitive error:&error]; 

NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:address options:0 range:NSMakeRange(0, [address length])]; 

NSLog(@"range of match = %d", rangeOfFirstMatch); 

if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) { 

    address = [address substringWithRange:rangeOfFirstMatch]; 
    NSLog(@"substring = %@", address8); 
    //i cant get the -333 but i don't know how to remove that..    

} 

任何想法?

預先感謝您!

回答

0

萬一有人絆倒在此,認爲接受答案的鏈接是模糊的,這裏是代碼:

address = @"333-333 Anywhere Lane"; 

NSError *error = NULL; 

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"-[0-9]*" options:NSRegularExpressionCaseInsensitive error:&error]; 

address = [regex stringByReplacingMatchesInString:address options:0 range:NSMakeRange(0, [address length]) withTemplate:@""]; 

NSLog(@"substring = %@", address8); 
相關問題