2013-10-25 32 views
0

我是Objective-C的初學者。如何用NSRegularExpression改變字符串

我有以下NSMutableString [email protected]"[abc][test][end]";

什麼是我應該使用以便刪除最後一個[]件(例如[結束])的最佳方式?

我有這樣的代碼:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\[]" options:0 error:NULL]; 
    NSArray *matches = [regex matchesInString:stringVal options:0 range:NSMakeRange(0, [stringVal length])]; 
    for (NSTextCheckingResult *match in matches) { 
     ?? what should i do here? 
    } 
+0

好吧,我明白你想刪除字符串結束,然後你想添加你的數組嗎? –

回答

0

我認爲你應該使用這個正則表達式模式"\\[.*?]"那麼你得到的三場比賽

['[abc]', '[test]', '[end]'] 

則可以只拿到範圍第三場比賽(檢查你有至少三個)

NSMutableString* stringVal= [NSMutableString stringWithString:@"[abc][test][end]"]; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[.*?]" options:0 error:NULL]; 
NSArray *matches = [regex matchesInString:stringVal options:0 range:NSMakeRange(0, [stringVal length])]; 
NSTextCheckingResult* match = matches[2]; 

NSMutableString* substring = [[stringVal substringToIndex:match.range.location] mutableCopy]; 
+0

我有以下工作:未知的轉義序列「」\「]」「。另外stringVal是一個NSMutableString。我應該怎麼寫,如果我想子字符串也是NSMutableString呢? –

+0

它不起作用。它不顯示任何[match rangeAtIndex:0] –

+0

NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:@「\ [。*?]」options:0 error:NULL]; NSArray * matches = [正則表達式matchesInString:stringval選項:0範圍:NSMakeRange(0,[stringval length])]; NSTextCheckingResult * match = [matches lastObject]; NSRange matchRange = [匹配範圍]; NSLog(@「match is:%@」,[stringval substringWithRange:[match rangeAtIndex:0]]); –

0

jbat是正確的,你應該修改的正則表達式。在此之後,所有你需要的是最後一場比賽,所以你可以使用

NSTextCheckingResult *match = [matches lastObject]; // Get the last match 
NSRange matchRange = [match range]; // Get the position of the match segment 
NSString *result = [stringVal stringByReplacingCharactersInRange:matchRange withString:@""]; // Replace the segment by an empty string. 
+1

這是正確的,如果他的正則表達式是正確的... – jbat100

+0

是的,我剛剛添加了你的建議。謝謝。 –

相關問題