我有一個字符串,例如:如何提取組匹配到數組?
<?xml version="xyzt" standalone="112.0" sxcx="xcxc"?>
我要提取的字符串數組,其中每個元素是字符串,如[version="xyzt", standalone="112.0", sxcx="xcxc"]
的屬性。
我試過使用string.scan(/\s\w+="\.*"/) do |block| puts block end
但我沒有得到結果..請告訴我爲什麼以及如何做到這一點。
我有一個字符串,例如:如何提取組匹配到數組?
<?xml version="xyzt" standalone="112.0" sxcx="xcxc"?>
我要提取的字符串數組,其中每個元素是字符串,如[version="xyzt", standalone="112.0", sxcx="xcxc"]
的屬性。
我試過使用string.scan(/\s\w+="\.*"/) do |block| puts block end
但我沒有得到結果..請告訴我爲什麼以及如何做到這一點。
string[/(?<=\<\?xml).*(?=\?>)/]
#⇒ 'version="xyzt" standalone="112.0" sxcx="xcxc"'
如果你需要用方括號括起來:
?[ << string[/(?<=\<\?xml).*(?=\?>)/] << ?]
#⇒ '[version="xyzt" standalone="112.0" sxcx="xcxc"]'
要獲得屬性的哈希:
string[/(?<=\<\?xml).*(?=\?>)/].split(/\s+/)
.map { |e| e.split('=') }
.to_h
#⇒ {
# "standalone" => "\"112.0\"",
# "sxcx" => "\"xcxc\"",
# "version" => "\"xyzt\""
# }
str = '<?xml version="xyzt" standalone="112.0" sxcx="xcxc"?>'
我假設你想生成數組:
['version="xyzt"', 'standalone="112.0"', 'sxcx="xcxc"']
你能做到這一點,如下所示:
arr = str.scan(/[a-z]+\=\S+/)
#=> ["version=\"xyzt\"", "standalone=\"112.0\"", "sxcx=\"xcxc\"?>"]
puts arr
# version="xyzt"
# standalone="112.0"
# sxcx="xcxc"?>
好了,正則表達式不匹配,該字符串什麼。所以沒有輸出。 –
我很確定你不想匹配零點或零點以上的文字點。使用http://regex101.com,這太棒了。 –
請考慮使用實際的XML解析器(例如[Nokogiri](http://www.nokogiri.org/))而不是[用正則表達式解析XML](https://stackoverflow.com/questions/1732348/regex-match -open標籤 - 除了-XHTML-自足標籤/)。 –