![](/img/trans.png)
[英]What is the best way to split a string to get all the substrings by Ruby?
[英]get multiple substrings from a string in Ruby
我有
tmp_body_symbols="things <st>hello</st> and <st>blue</st> by <st>orange</st>"
str1_markerstring = "<st>"
str2_markerstring = "</st>"
frags << tmp_body_symbols[/#{str1_markerstring}(.*?)#{str2_markerstring}/m, 1]
碎片是“你好”,但我想要[“你好”,“藍色”,“橙色”]
我該怎么做?
使用scan
:
tmp_body_symbols.scan(/#{str1_markerstring}(.*?)#{str2_markerstring}/m).flatten
另請參閱: String#scan
Ruby文檔 。
您可以使用Nokogiri解析HTML / XML
require 'open-uri'
require 'nokogiri'
doc = Nokogiri::HTML::Document.parse("things <st>hello</st> and <st>blue</st> by <st>orange</st>")
doc.css('st').map(&:text)
#=> ["hello", "blue", "orange"]
更多信息: http : //www.nokogiri.org/tutorials/parsing_an_html_xml_document.html
您可以像@Doorknob一樣使用捕獲組來執行此操作,也可以不使用捕獲組來執行此操作,方法是使用(“零寬度”)正向后看和正向先行:
tmp = "things <st>hello</st> and <st>blue</st> by <st>orange</st>"
s1 = "<st>"
s2 = "</st>"
tmp.scan(/(?<=#{ s1 }).*?(?=#{ s2 })/).flatten
#=> ["hello", "blue", "orange"]
(?<=#{ s1 })
值為(?<=<st>)
,是正向后看。 (?=#{ s2 })
計算結果為(?=</st>)
,是正向后看。 ?
后面的.*
使其“非貪婪”。 沒有它: tmp.scan(/(?<=#{ s1 }).*(?=#{ s2 })/).flatten
#=> ["hello</st> and <st>blue</st> by <st>orange"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.