簡體   English   中英

使用RegExp(Ruby)從HTML標簽提取字符串

[英]Extract string from HTML tags using RegExp (Ruby)

我想從字符串<h1>test</h1><div>toast</div>提取“ toast”。 什么正則表達式可以隔離這樣的字符串?

編輯:感謝糾正格式的用戶。

更多信息:始終只有div標簽的一個實例,內部信息可能會更改,但同一字符串中永遠不會再有另一個div標簽(該字符串大於給定的樣本)

謝謝!

您可以使用Nokogiri

require 'nokogiri'

doc = Nokogiri::HTML::Document.parse("<div> test </div> <div> toast </div>")
doc.css('div').map(&:text)
# => [" test ", " toast "]

require 'nokogiri'

doc = Nokogiri::HTML::Document.parse("<h1>test</h1><div>toast</div>")
doc.at_css('div').text
# => "toast"

我們需要更多信息。 如果字符串恰好是"<h1>test</h1><div>toast</div>" ,則類似天真

regex = /<h1>test<\/h1><div>([^<]*)<\/div>/
found = "<h1>test</h1><div>toast</div>".match(regex)[1]
# => "toast"

會工作。 我目前的最佳猜測是您期望

<h1>*</h1><div>*</div>

然后使用這個:

regex = /<h1>[^<]*<\/h1><div>([^<]*)<\/div>/
found = "<h1>any string can go here</h1><div>toast</div>".match(regex)[1]
# => "toast"

請注意,如果任一標簽中有任何嵌套元素,則此操作將中斷。 一個更強大的解決方案是使用Nokogiri。 和你老板談談。

實際上,這不是正則表達式通常要做的事情……並且有充分的理由,但是如果您必須且由於您說過,其中的div不會超過一個……這應該對您有用:

(?<=<div>).*(?=</div>)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM