NSScanner解析文件

时间:2011-03-07 16:58:46

标签: iphone objective-c xcode icalendar nsscanner

我正在尝试使用NSScanner来解析一个ics文件(为了解析而已经转换为文本文件),即:calendar file.txt

这是文本文件的格式:

BEGIN:VEVENT  
DTSTAMP:20101129T061152Z  
UID:101139897313172011030314:00  
SUMMARY:14:00 - SYSI30251 - CB100 - SEM B  
DESCRIPTION:14:00 - 15:00, SYSI30251 - Module Name<br />Group: B <b>Seminar with Lecturer in room(s) (Clif) Computing Bldg 100  
DTSTART;TZID=Europe/London:20110303T140000  
DTEND;TZID=Europe/London:20110303T150000  
SEQUENCE:2  
END:VEVENT  
BEGIN:VEVENT  
DTSTAMP:20101129T061152Z  
UID:1011558905160182011030315:00  
SUMMARY:15:00 - COMP30251 - CFL015 - LEC    
DESCRIPTION:15:00 - 16:00, COMP30251 - Project Management<br /> Lecture with Lecturer in room(s) (Clif) Centre For Learning 015  
DTSTART;TZID=Europe/London:20110303T150000  
DTEND;TZID=Europe/London:20110303T160000  
SEQUENCE:2  
END:VEVENT  

以上是文件的格式。以下是我的代码:

NSString *path = [[NSBundle mainBundle] pathForResource:@"180946_icalfile" ofType:@"txt"];
    NSString *fileComponents = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSArray *lines = [fileComponents componentsSeparatedByString:@"\n"];


    NSEnumerator *nse = [lines objectEnumerator];
    NSString *mod;
    while(fileComponents = [nse nextObject]) {
        NSString *stringBetweenBrackets = nil;
        NSScanner *scanner = [NSScanner scannerWithString:fileComponents];
        [scanner scanUpToString:@"," intoString:nil];
        [scanner scanString:@"" intoString:nil];
        [scanner scanUpToString:@"DTSTART" intoString:&stringBetweenBrackets];

        NSLog(@"%@", stringBetweenBrackets);

基本上我想存储所有'DESCRIPTIONS'并将它们存储为变量或作为数组的一部分。目前,代码将描述输出到控制台,我想将它们保存为变量。有人能告诉我这是怎么做到的吗?

2 个答案:

答案 0 :(得分:3)

我无法确定这正是您想要的,但http://parsekit.com/可以让您的工作更轻松。它将使源代码成为令牌数组。并且您可以迭代每个令牌以过滤“DESCRIPTIONS”令牌,并收集以下令牌以进行处理。

答案 1 :(得分:2)

尝试使用以下正则表达式而不是使用NSScanner:

/DESCRIPTION:([^\n]+)\n/is