2012-05-09 122 views
0

我試圖使用NSRegularExpressions解析HTML頁面.. 頁是這個HTML代碼的重複:解析HTML NSRegularExpression

<div class="fact" id="fact66">STRING THAT I WANT</div> <div class="vote"> 
<a href="index.php?p=detail_fact&fact=106">#106</a> &nbsp; &nbsp; 
<span id="p106">246080/8.59 </span> &nbsp; &nbsp; 
<span id="f106" class="vote2"> 
<a href="#" onclick="xajax_voter(106,3); return false;">(+++)</a> 
<a href="#" onclick="xajax_voter(106,2); return false;">(++)</a> 
<a href="#" onclick="xajax_voter(106,1); return false;">(+)</a> 
<a href="#" onclick="xajax_berk(106); return false;">(-)</a></span> 
<span id="ve106"></span> 
</div> 

所以,i'ld想獲得股利之間的串

<div class="fact" id="fact66">STRING THAT I WANT</div> 

所以我做了一個正則表達式看起來像這樣

<div class="fact" id="fact[0-9].*\">(.*)</div> 

現在,在我的C賦,我使用這個實現:

NSString *htmlString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.myurl.com"] encoding:NSASCIIStringEncoding error:nil]; 
NSRegularExpression* myRegex = [[NSRegularExpression alloc] initWithPattern:@"<div class=\"fact\" id=\"fact[0-9].*\">(.*)</div>\n" options:0 error:nil]; 
    [myRegex enumerateMatchesInString:htmlString options:0 range:NSMakeRange(0, [htmlString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) { 
     NSRange range = [match rangeAtIndex:1]; 
     NSString *string =[htmlString substringWithRange:range]; 
     NSLog(string); 
    }]; 

但它沒有返回值...我測試了我的正則表達式在Java和PHP和它的偉大工程,我在做什麼錯?

由於

+1

Just a FYI http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – Joe

+0

Oblicatory,[「使用正則表達式來解析HTML:爲什麼不? 「](http://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not) –

回答

1

嘗試使用此正則表達式:

@"<div class=\"fact\" id=\"fact[0-9]*\">([^<]*)</div>" 

正則表達式:

fact[0-9].* 

指:事實上,隨後在0和9之間的一個數,隨後通過任何字符重複任意倍。

我也建議使用:的

([^<]*) 

代替

(.*) 

到兩個div之間的匹配,從而應對正則表達式的貪婪,或者:

(.*?) 

(?會使正則表達式非貪婪,所以它停止在</div>的第一個實例。

+0

編輯:刪除\ n在最後,我沒有見過它.. – sergio

+0

非常感謝!只是一個問題,我應該如何修改它以獲取「 246080/8.59」(就像這裏,我想要'246080/8.59')? – Abel

+0

不用客氣;對於跨度,請使用:'@「([^ <]*)」' – sergio