2013-05-10 129 views
1

我需要解析一個字符串,如[abc]000,我想得到的是一個包含abc000的數組。有沒有簡單的方法來做到這一點?如何解析字符串格式,如[***] ***?

我用這樣的代碼:

NSString *sampleString = @"[abc]000"; 
NSArray *sampleParts = [sampleString componentsSeparatedByString:@"]"]; 
NSString *firstPart = [[[sampleParts objectAtIndex:0] componentsSeparatedByString:@"["] lastObject]; 
NSString *lastPart = [sampleParts lastObject]; 

但它的效率不高,並沒有檢查字符串是否在格式如[**] **。

+3

['NSRegularExpression'](http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html) – millimoose 2013-05-10 01:29:28

+2

[NSScanner](https://developer.apple .com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSScanner_Class/Reference/Reference.html) – vikingosegundo 2013-05-10 01:51:15

+0

我們的答案是否有助於您? – lnafziger 2013-05-24 20:20:02

回答

1

對於這個簡單的模式,可以只解析喜歡自己:

NSString *s = @"[abc]000"; 
NSString *firstPart = nil; 
NSString *lastPart = nil; 
if ([s characterAtIndex: 0] == '[') { 
    NSUInteger i = [s rangeOfString:@"]"].location; 
    if (i != NSNotFound) { 
     firstPart = [s substringWithRange:NSMakeRange(1, i - 1)]; 
     lastPart = [s substringFromIndex:i + 1]; 
    } 
} 

或者你可以學習使用NSScanner類。

0

嘗試這樣,

NSString *sampleString = @"[abc]000"; 
NSString *pNRegex = @"\\[[a-z]{3}\\][0-9]{3}"; 
NSPredicate *PNTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pNRegex]; 
BOOL check=[PNTest evaluateWithObject:sampleString ]; 
NSLog(@"success:%i",check); 

如果success來作爲1,那麼您可以分離到字符串數組執行的操作。

1

一如既往,有很多方法可以做到這一點。

OPTION 1
如果這些固定長度的字符串(每個部分始終是三個字符),那麼你可以簡單地直接獲取字符串:

NSString *sampleString = @"[abc]000"; 
NSString *left = [sampleString substringWithRange:NSMakeRange(1, 3)]; 
NSString *right = [sampleString substringWithRange:NSMakeRange(5, 3)]; 
NSArray *parts = @[ left, right ]; 
NSLog(@"%@", parts); 

選項1(縮短)

NSArray *parts = @[ [sampleString substringWithRange:NSMakeRange(1, 3)], 
        [sampleString substringWithRange:NSMakeRange(5, 3)] ]; 
NSLog(@"%@", parts); 

選項2
如果他們並不總是三個字符,那麼你可以使用NSScanner

NSString *sampleString = @"[abc]000"; 

NSScanner *scanner = [NSScanner scannerWithString:sampleString]; 

// Skip the first character if we know that it will always start with the '['. 
// If we can not make this assumption, then we would scan for the bracket instead. 
scanner.scanLocation = 1; 

NSString *left, *right; 

// Save the characters until the right bracket into a string which we store in left. 
[scanner scanUpToString:@"]" intoString:&left]; 

// Skip the right bracket 
scanner.scanLocation++; 

// Scan to the end (You can use any string for the scanUpToString that doesn't actually exist... 
[scanner scanUpToString:@"\0" intoString:&right]; 

NSArray *parts = @[ left, right ]; 
NSLog(@"%@", parts); 

結果(所有選項)

2013-05-10 00:25:02.031 Testing App[41906:11f03] (
    abc, 
    000 
) 

注意
所有這些假設以及形成字符串,所以你應該包括你自己的錯誤檢查。