"IOS" Regular expression crawl Web page data making small dictionary

Source: Internet
Author: User

Applications do not have to provide their own data, there are ready-made data to learn to use it.

The internet is very large, and various search engines crawl around every day. This article uses regular expression to crawl the data of the website to make a small dictionary.

First, the use of regular expressions

1. Identify the matching scheme, which is the pattern

2. Instantiate nsregularexpression with pattern

3. Start the match with a matching method.

Match once: You can use the firstmatch method

Multiple matches: You can use the matchs method


Regular expression Comparison table: (Found on the Internet a very good tables, regular expressions are common in each language)

Http://www.jb51.net/shouce/jquery1.82/regexp.html


Here is the test code, which can match:xn4545945

Test the regular expression with-(void) findanswerinhtmltest {    NSString *srcstr = @ "http://blog.csdn.net/xn4545945";        NSString *pattern = @ "xn[^\\s]*";  Matches any non-whitespace character//instantiation regular expression that begins with Xn, requires two options to be specified//nsregularexpressioncaseinsensitive  ignore case// Nsregularexpressiondotmatcheslineseparators let. Ability to match newline nsregularexpression *regex = [[Nsregularexpression alloc] Initwithpattern:pattern options:nsregularexpressioncaseinsensitive | Nsregularexpressiondotmatcheslineseparators Error:nil];    Match out result set nstextcheckingresult *checkresult = [Regex firstmatchinstring:srcstr options:nsmatchingreportcompletion Range:nsmakerange (0, Srcstr.length)];    Remove the found content. NSString *result = [Srcstr substringwithrange:[checkresult rangeatindex:0];    NSLog (@ "Data is----->%@", result);}


Second, crawl web data, and make small dictionaries

Use Sea Word as query dictionary to fetch data. http://dict.cn

Directly after the URL stitching query words can query, such as query "Hello", that is Http://dict.cn/hello

View the source code of the Web page such as: That is grabbed out (hello) hello;



Tips:

(.*?)to take out what you want..brackets Surroundto remove.It 's enough to grab the web..*. indicates a match for any character**indicates repetition0to several times*?indicates as few matches as possible.*will beneed to remove thewith(.*?)Replace.large spaces for line wrapping.*?Replace,representsIgnore.
combined with the browser's search function,Find in Source code,look at the key words selected isNo Duplicatesof the.(more convenient when looking for)*SelectA little bit bigger.The Block(the label hasIDmarked as good),can doonly.(If you choose too small,There may be a lot of small labels that repeat in the Web page very often)*thenMultiple callsRegular Expression Methods,graduallyNarrow the range.*quotation marksneed to be escaped(Add back Slash).Englishneed to%escaped. (Use Method)
directly on the code:
@implementation xnspider-(void) Loadhtmlwithword: (NSString *) word {//1. Send an HTML request to get the returned page. (  Convert to String) nsstring *urlstring = [NSString stringwithformat:@ "%@%@", Kbaseurl, Word]; Stitching request URL urlstring = [urlstring stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];  Chinese escape nsurl *url = [Nsurl urlwithstring:urlstring]; Get urlnsurlrequest *request = [Nsurlrequest requestwithurl:url cachepolicy:nsurlrequestuseprotocolcachepolicy TIMEOUTINTERVAL:5.0F]; [Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] CompletionHandler: ^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) {//The resulting data is converted to a string nsstring *html = [[NSString all]    OC] Initwithdata:data encoding:nsutf8stringencoding];//NSLog (@ "%@", HTML); 2. Match (regular expression filter) desired from the returned string.    (also write a method findanswerinhtml)//Then pass the result through the proxy to the main thread, to update the UI nsstring *result = [self findanswerinhtml:html];    NSLog (@ "%@", result); if ([Self.delegate respondstoselector: @selector (finishspider:)]) {[Self.delegate Finishspider:result]; The finished result is passed to the UI thread by proxy.}}];} /** * Regular expression matching string core method * * @param HTML input of the entire page string * * @return return matching results */-(NSString *) findanswerinhtml: (NSString *) HTML {//will need to be removed with (. *?) Replace. Large spaces for line wrapping, etc. * instead, indicates ignore. NSString *pattern = @ "<ul class=\" Dict-basic-ul\ ">.*?<li><span> (. *?) </span><strong> (. *?) </strong></li> ";//instantiate regular expression, you need to specify two options//nsregularexpressioncaseinsensitive ignore case// Nsregularexpressiondotmatcheslineseparators let. Ability to match newline nsregularexpression *regex = [[Nsregularexpression alloc] Initwithpattern:pattern options:nsregularexpressioncaseinsensitive | Nsregularexpressiondotmatcheslineseparators error:nil];//matches the result set nstextcheckingresult *checkResult = [regex firstmatchinstring:html options:nsmatchingreportcompletion range:nsmakerange (0, Html.length)];//remove the found content. The numbers correspond to the first parentheses (. *?), and the output matches the whole sentence by 0 o'clock. NSString *result = [html Substringwithrange:[checkresult rangeatindex:2]; NSLog (@ "Data is----->%@", result); return result;}

The match results are finally used to update the UI with a proxy to the main thread.The program interface is as follows: (after searching for Android, the data found in the Web page is "robot")

the error handling is not done here.

The program source code is as follows:http://download.csdn.net/detail/xn4545945/7619349

Reprint Please specify source:http://blog.csdn.net/xn4545945


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.