2014-09-05 32 views
1

,我有以下的HTML一塊我想與gregexpr功能R中運行的正則表達式gregexpr函數返回不同的結果的Perl是否是真還是假

<div class=g-unit> 
<div class=nwp style=display:inline> 
<input type=hidden name=cid value="22144"> 
<input autocomplete=off class=id-fromdate type=text size=10 name=startdate value="Sep 6, 2013"> - 
<input autocomplete=off class=id-todate type=text size=10 name=enddate value="Sep 5, 2014"> 
<input id=hfs type=submit value=Update style="height:1.9em; margin:0 0 0 0.3em;"> 
</div> 
</div> 
</div> 
<div id=prices class="gf-table-wrapper sfe-break-bottom-16"> 
<table class="gf-table historical_price"> 
<tr class=bb> 
<th class="bb lm lft">Date 
<th class="rgt bb">Open 
<th class="rgt bb">High 
<th class="rgt bb">Low 
<th class="rgt bb">Close 
<th class="rgt bb rm">Volume 
<tr> 
... 
... 
</table> 
</div> 

我想提取表通過使用下面的正則表達式

<table\\s+class="gf-table historical_price">.+< 

當我用Perl運行gregexpr功能部件從這個網站= FALSE它工作正常,我得到的結果 但是如果我用Perl =運行它真我回去沒事。它似乎不匹配它

有誰知道爲什麼結果不同,只是打開和關閉Perl? 非常感謝提前!

+4

[你不應該用正則表達式解析HTML](http://stackoverflow.com/a/1732454/725418)。改用解析器。 – TLP 2014-09-05 17:14:15

+0

我不能輕易獲得張貼的內容,而是建立在@TLP上,像這樣(使用XML包):doc < - htmlTreeParse('your countent URL',useInternal = TRUE); xpathSApply(doc,「// divclass ='gf-table historical_price'] // th」,xmlValue,trim = TRUE) – lawyeR 2014-09-05 19:29:15

回答

6

看來,在正則表達式的擴展模式下,the dot is able to match newline characters,在perl模式下不是這種情況。爲了使其在perl的模式下工作,你需要使用(?s)修改,使點能夠匹配得換行字符:

> m <- gregexpr('(?s)<table\\s+class="gf-table historical_price">.+</table>', str, perl = TRUE) 

在許多正則表達式的口味,點不匹配,默認換行符,大概逐行工作更加方便。

inline修飾符(?s)中的s代表「單行」。換句話說,這意味着即使有換行符,整個字符串也被視爲單行(對於點)。

4

您需要使用內聯(?s)修飾符強制點匹配所有字符,包括換行符。

perl=T自變量切換到實現正則表達式模式匹配的(PCRE)庫。

gregexpr('(?s)<table\\s+class="gf-table historical_price">.+</table>', x, perl=T) 

但是,正如註釋中所述,建議使用解析器來執行此操作。我會開始使用XML庫。

cat(paste(xpathSApply(htmlParse(html), '//table[@class="gf-table historical_price"]', xmlValue), collapse = "\n")) 
相關問題