[英]How do get value tag in Ruby using regex?
我有標簽:
val = "<a href=\"https://mobile.twitter.com\" rel=\"nofollow\">Mobile Web</a>"
在我的測試中:
val[/(>.*<)/]
回報:
>Mobile Web<
我想返回文本:
Mobile Web
您可以使用Nokogiri進行解析:
require 'nokogiri'
html = '<a href="https://mobile.twitter.com" rel="nofollow">Mobile Web</a>'
elem = Nokogiri(html)
puts elem.text
您可以使用match並用括號選擇想要的部分
/>(.*)</.match(val)[1]
我會使用諸如hpricot或nokogiri之類的html解析庫進行html解析,因為正則表達式可能有很多極端的情況,直到在某個地方運行了幾個月甚至休息之后,它才變得明顯!
向前/向后看將起作用。
val[/(?<=>)(.*)(?=<)/]
require 'nokogiri'
html = '<a href="https://mobile.twitter.com" rel="nofollow">Mobile Web</a>'
elem = Nokogiri::HTML::DocumentFragment.parse(html).child
p elem.text #=> Mobile Web
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.