Tuesday, August 14, 2012

How to use NSScanner on NSString.

This is quiet useful in terms of parsing a simple static webpage, also pick certain kind of words from the NSString.

Lets say we have following snippet from a html file.


NSString *htmlString=


< div id="topLeft" class="news" style="padding-top:3px"
onMouseOver="style.color='white';style.backgroundColor='#F0ABFF'" onMouseOut="style.color='black';style.backgroundColor='#000000'"><style="text-decoration:none;color:black" onMouseOver="style.color='white'" onMouseOut="style.color='black'"href="reetu/test/news.htm" target="_blank">Latest News</a>


Now I want to extract the url, text and div id from this html file snippet. Following code will give you that.


     NSScanner *rScanner = [NSScanner scannerWithString:string];
     NSString *divID=@"";
    [rScanner scanString:@"<div id=\"" intoString:NULL];
    [rScanner scanUpToString:@"class=\"news\"" intoString:&courseID];

     divID=[divID stringByReplacingOccurrencesOfString:@" " withString:@""];
     divID=[divID stringByReplacingOccurrencesOfString:@"\"" withString:@""]; 
     divID=[divID stringByReplacingOccurrencesOfString:@"<divid=" withString:@""]; 
     NSLog(@"divID=%@",divID);           

/*Instead of above 3 lines you could also do [rScanner scanUpToString: instead of scanString:
    

    NSString *rURL=@"";
    [rScanner scanUpToString:@"href=\"" intoString:NULL];
    [rScanner scanUpToString:@">" intoString:&rURL];
     rURL=[rURL stringByReplacingOccurrencesOfString:@"href=\"" withString:@""];
     rURL=[rURL stringByReplacingOccurrencesOfString:@"target=\"_blank\"" withString:@""];
     rURL=[rURL stringByReplacingOccurrencesOfString:@"\" " withString:@""];
     NSLog(@"rURL=%@",rURL);






   NSString *rName=@"";
   [rScanner scanUpToString:@"</a>" intoString:&rName];
    rName=[courseName stringByReplacingOccurrencesOfString:@">" withString:@""];
    NSLog(@"rName=%@",rName);
    

    


    




It will print following results:


divID=topLeft
rURL=reetu/test/news.htm
rName=Latest News



Read More: https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Strings/Articles/Scanners.html


2 comments:

  1. Thanks For Sharing Information
    Yaaron Studios is one of the rapidly growing editing studios in Hyderabad. We are the best Video Editing services in Hyderabad. We provides best graphic works like logo reveals, corporate presentation Etc. And also we gives the best Outdoor/Indoor shoots and Ad Making services.
    Best video editing services in Hyderabad,ameerpet
    Best Graphic Designing services in Hyderabad,ameerpet­
    Best Ad Making services in Hyderabad,ameerpet­

    ReplyDelete