2011-11-25 55 views
0

我想获取两个标记之间的文本。ruby​​正则表达式扫描多个匹配

<b> foo</b>bar<br/> =>bar

我尝试使用'<b>asdasd</b>qwe<br/>'.scan(/<b>[a-zA-Z0-9]*<\/b>(.*)<br\/>/),它给了我正确的结果。

但是当我试试这个:

'<b>exclude</b>op1<br/>exclude 2<b>exclude</b>op2<br/>exclude 2<b>exclude</b>op3<br/>exclude 2'.scan(/<b>[a-zA-Z0-9]*<\/b>(.*)<br\/>/) { |ele| 
puts ele 
} 

它的第一<b>标签和最后<br/>标签相匹配,并返回整个字符串我期待的比赛

+1

相关问题:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self- contained-tags –

回答

8

变化(.*)的数组(.*?)使它ungreedy

/<b>[a-zA-Z0-9]*<\/b>(.*?)<br\/>/ 

测试

[2] pry(main)> '<b>exclude</b>op1<br/>exclude 2<b>exclude</b>op2<br/>exclude 2<b>exclude</b>op3<br/>exclude 2'.scan(/<b>[a-zA-Z0-9]*<\/b>(.*?)<br\/>/) { |ele| 
[2] pry(main)* puts ele 
[2] pry(main)* } 
op1 
op2 
op3 
+2

你不能用正则表达式解析HTML。 – Reactormonk

9

而不是使用上的HTML使用正则表达式引入nokogiri的:

Nokogiri::HTML.fragment(str).css('b').each do |b| 
    puts b.next.text 
end