简体   繁体   中英

Capture character from string

If I have this string:

"<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>"

How can I capture this value:

N/A

As you can see I want to scan for what is the value of the <p class='attachment'>

Attempt:

conversation.scan(/<p class='attachment'>/)

But that doesn't get the value of what is in the p tag.

If you want to do this more often than not, I would consider using an HTML parser such as Nokogiri because writing regex for every such need is painful.

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"

You can match N/A with

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

尝试这个

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM