从字符串中捕获字符

问题描述 投票:2回答:3

如果我有这个字符串:

"<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标签中的值。

ruby-on-rails ruby
3个回答
4
投票

如果你想经常这样做,我会考虑使用像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"

2
投票

你可以匹配N/A

conversation[/(?<=<p class='attachment'>).*?(?=<\/p>)/]                          
 #=> "N/A" 

2
投票

试试这个

conversation.scan(/(?<=<p class='attachment'>).*?(?=<\/p>)/).first

© www.soinside.com 2019 - 2024. All rights reserved.