使用NSScanner来解析字符串

时间:2011-07-27 13:14:12

标签: cocoa nsstring string-parsing nsscanner

要解析的两行字符串是:

00:02.0 VGA compatible controller [0300]: Intel Corporation 82945G/GZ Integrated Graphics Controller [8086:2772] (rev 02)
00:02.1 Display controller [0380]: Intel Corporation 82945G/GZ Integrated Graphics Controller [8086:2776] (rev 02)

获取这些字符串:

(从第1行开始)

  • VGA兼容控制器
  • Intel Corporation 82945G / GZ集成图形控制器
  • [8086:2772]

(从第2行开始)

  • 显示控制器
  • Intel Corporation 82945G / GZ集成图形控制器
  • [8086:2776]

现在我的开始代码是:

NSScanner *scn = [NSScanner scannerWithString:strtoparse];
NSString *devtype;      
while ([scn isAtEnd] == NO)
    {
       if( [scn scanUpToCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString:NULL] &&
        [scn scanUpToString:@"[" intoString:&devtype]);
    }

并且这不起作用。我甚至无法从文档中了解扫描仪。那么有人可以发布工作代码吗?

1 个答案:

答案 0 :(得分:3)

快速摘要:

NSString *theString = @"00:02.0 VGA compatible controller [0300]: Intel Corporation 82945G/GZ Integrated Graphics Controller [8086:2772] (rev 02)\n00:02.1 Display controller [0380]: Intel Corporation 82945G/GZ Integrated Graphics Controller [8086:2776] (rev 02)";

NSScanner *theScanner = [NSScanner scannerWithString:theString];

NSCharacterSet *space = [NSCharacterSet characterSetWithCharactersInString:@" "];
NSCharacterSet *bracket = [NSCharacterSet characterSetWithCharactersInString:@"["];
NSCharacterSet *linebreak = [NSCharacterSet newlineCharacterSet];

NSString *type;
NSString *name;
NSString *number;

while (![theScanner isAtEnd]) 
{
    [theScanner scanUpToCharactersFromSet:space intoString:nil] ;
    [theScanner scanUpToCharactersFromSet:bracket intoString:&type]; 
    [theScanner scanUpToCharactersFromSet:space intoString:nil] ;
    [theScanner scanUpToCharactersFromSet:bracket intoString:&name]; 
    [theScanner scanUpToCharactersFromSet:space intoString:&number]; 
    [theScanner scanUpToCharactersFromSet:linebreak intoString:nil] ;

    NSLog(type);
    NSLog(name);
    NSLog(number);
}

输出:

VGA compatible controller 
Intel Corporation 82945G/GZ Integrated Graphics Controller 
[8086:2772]
Display controller 
Intel Corporation 82945G/GZ Integrated Graphics Controller 
[8086:2776]