2013-10-18 33 views
1

我有一個NSString的NSString,當NSlogged返回此:提取文本形式使用關鍵詞

device status: (SOME LETTERS), session code: (SOME NUMBERS) 

如何從最初的字符串中提取兩個沒有實際切割字符串有類似:

NSString* str1 = text for "device status"; 
NSString* str1 = text for "session code"; 

回答

2

交朋友NSRegularExpression

NSString* str = @"device status: dead, session code: 666"; 

NSError *err; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"device status: (//w*), session code: (//d*)" options:0 error:&err]; 
if (err) { 
    NSLog(@"Returned an error: %@", [err localizedDescription]); 
} 
NSArray* matches = [regex matchesInString:str options:0 range:NSMakeRange(0, [str length])]; 
// get the first match 
NSTextCheckingResult *match = matches[0]; 

// extract the groups 
NSString *deviceStatus = [str substringWithRange:[match rangeAtIndex:1]]; 
NSString *sessionCode = [str substringWithRange:[match rangeAtIndex:2]]; 
+0

即使其他建議的方法是要短得多,我剔這是接受,因爲它正是我一直在尋找:)感謝 – Alessandro

+0

的方法這段代碼在NSTextCheckingResult * match = matches [0]中導致崩潰。 – Alessandro

+0

意思是沒有匹配,我建議你玩http://regexpal.com看看你是否已經正確地形成了你的正則表達式模式。 – lawicko

3

簡單的代碼會像。

如可以使用componentsSeparatedByString

- (NSArray *)componentsSeparatedByString:(NSString *)separator 

裝置返回包含從已經由一個給定的分離器分開的接收器子陣列。

NSString *string = @"device status: (SOME LETTERS), session code: (SOME NUMBERS)"; 
NSArray *array = [string componentsSeparatedByString:@","]; 
NSArray *one = [[array objectAtIndex:0] componentsSeparatedByString:@":"]; 
NSArray *two = [[array objectAtIndex:1] componentsSeparatedByString:@":"]; 

NSLog(@"key = %@ and Value = %@",[one objectAtIndex:0],[one objectAtIndex:1]); 
NSLog(@"key = %@ and Value = %@",[two objectAtIndex:0],[two objectAtIndex:1]); 
0
NSArray *commaSeparated = [originalString componentsSeparatedByString:@", "]; 
NSArray *colonSeparated1 = [commaSeparated[0] componentsSeparatedByString:@": "; 
NSArray *colonSeparated2 = [commaSeparated[1] componentsSeparatedByString:@": "; 
NSString *statusString = colonSeparated1[1]; 
NSString *sessionString = colonSeparated2[1];