2012-07-18 30 views
1

大家好,我有一個html代碼作爲代碼波紋管。我想進去<a>(.*)</a>在Ruby中用正則表達式解析html

我想要得到這樣的結果的文本:

data 1 : hello1 
data 2 : hello2 
data 3 : hello3 

從輸入:

<a> 
hello1 
</a> 
<a> 
hello2 
</a> 
<a> 
hello3 
</a> 
+6

[不解析與正則表達式HTML(http://stackoverflow.com/questions/1732348/regex-match-開放式標籤,除了-XHTML-自足標籤/ 1732454#1732454)。 – Seki 2012-07-18 11:32:57

+0

請使用像[Nokogiri](http://nokogiri.org/)這樣的專用HTML解析器,而不是 – Stefan 2012-07-18 11:46:10

回答

2

要在兩點意見擴張,下面引入nokogiri代碼將工作爲你舉例。您可以使用xpath或CSS。一個專用的解析器比滾動你自己的正則表達式要強大得多。

> require 'nokogiri' 
=> true 
> doc = Nokogiri::HTML("<a>hello1</a><a>hello2</a><a>hello3</a>") 
=> #<Nokogiri::HTML::Document:0x3ffec2494f48 name="document" children=[#<Nokogiri::XML::DTD:0x3ffec2494bd8 name="html">, #<Nokogiri::XML::Element:0x3ffec2494458 name="html" children=[#<Nokogiri::XML::Element:0x3ffec2494250 name="body" children=[#<Nokogiri::XML::Element:0x3ffec2494048 name="a" children=[#<Nokogiri::XML::Text:0x3ffec2493e40 "hello1">]>, #<Nokogiri::XML::Element:0x3ffec249dc88 name="a" children=[#<Nokogiri::XML::Text:0x3ffec249da80 "hello2">]>, #<Nokogiri::XML::Element:0x3ffec249d878 name="a" children=[#<Nokogiri::XML::Text:0x3ffec249d670 "hello3">]>]>]>]> 
> doc.css('a').each { |node| p node.text } 
"hello1" 
"hello2" 
"hello3" 
=> 0 

更新:如果您尚未安裝nokogiri寶石,您將需要它。

sudo gem install nokogiri 

根據您的設置,您可能還需要預先

require 'rubygems' 
+0

LoadError:無法從C:/Ruby193/lib/ruby/site_ruby/1.9.1/rubygems/加載此類文件 - nokogiri custom_require.rb:36:i n'require' from i got:C:/Ruby193/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:i n'require' from(irb ):1 from C:/ Ruby193/bin/irb:12:in'

' – 2012-07-18 12:06:37

+0

10x:D it works – 2012-07-18 12:19:30