如果我有这个字符串:
"<div class='name-and-date'><strong>Bartholome Hilpert MD - Dec 21,
12:38 PM Eastern</div></strong><div class='note-contents'>-
another</div><div> Attachment: <p class='attachment'>N/A</p></div></span>"
我如何捕获此值:
N/A
如你所见,我想扫描<p class='attachment'>
的价值
尝试:
conversation.scan(/<p class='attachment'>/)
但这并不能获得p标签中的值。
如果你想经常这样做,我会考虑使用像Nokogiri这样的HTML解析器,因为为每个这样的需求编写正则表达式是很痛苦的。
require 'nokogiri'
html = Nokogiri::HTML("<div class='name-and-date'><strong>Bartholome Hilpert MD - Dec 21, 12:38 PM Eastern</div></strong><div class='note-contents'>- another</div><div> Attachment: <p class='attachment'>N/A</p></div></span>")
html.at_css('p.attachment').text # => "N/A"
你可以匹配N/A
conversation[/(?<=<p class='attachment'>).*?(?=<\/p>)/]
#=> "N/A"
试试这个
conversation.scan(/(?<=<p class='attachment'>).*?(?=<\/p>)/).first