DynastySS
DynastySS

Reputation: 395

Nokogiri: how to display partial output of the css selector?

Say that I am pulling the address from div.body h3 a. The issue is, what if I only wanted part of the address? For example, if the html read: <a href="/usa/sale/100-happy-street">100 Happy Street #PH </a>

How do I say, I only want to display the PH?

Upvotes: 1

Views: 115

Answers (1)

Phrogz
Phrogz

Reputation: 303178

anchor = doc.at('div.body h3 a') # the <a …>…</a> element
link   = anchor.text             # "100 Happy Street #PH "
last   = link[ /#([^#]+)/, 1 ]      # "PH"

This regex (which has nothing to do with Ruby on Rails or Nokogiri) extracts all text from a string that comes after the last # in the string, assuming that there is at least one #. You could get a similar result with last = link.split("#").last.

Upvotes: 1

Related Questions