开发者

use NSScanner to parse string

The two-line string to parse is:

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)

to get these strings out:

(from 1st line)

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

(from 2nd line)

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

Now my starting code is:

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

and this aint working. I cant even understand the scanner from the docs. So can someone post working code?


Quick snippet:

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);
}

Output:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜