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.
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'"><a 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=@"";
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);
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);
[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);
[rScanner scanUpToString:@"</a>" intoString:&rName];
rName=[courseName stringByReplacingOccurrencesOfString:@">" withString:@""];
NSLog(@"rName=%@",rName);
It will print following results:
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