2016-07-27 63 views
0

我有一个字符串,例如:如何提取组匹配到数组?

<?xml version="xyzt" standalone="112.0" sxcx="xcxc"?> 

我要提取的字符串数组,其中每个元素是字符串,如[version="xyzt", standalone="112.0", sxcx="xcxc"]的属性。

我试过使用string.scan(/\s\w+="\.*"/) do |block| puts block end但我没有得到结果..请告诉我为什么以及如何做到这一点。

+0

好了,正则表达式不匹配,该字符串什么。所以没有输出。 –

+0

我很确定你不想匹配零点或零点以上的文字点。使用http://regex101.com,这太棒了。 –

+3

请考虑使用实际的XML解析器(例如[Nokogiri](http://www.nokogiri.org/))而不是[用正则表达式解析XML](https://stackoverflow.com/questions/1732348/regex-match -open标签 - 除了-XHTML-自足标签/)。 –

回答

0
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\"" 
# } 
+0

他想要数组属性。 –

+0

@SergioTulentsev的确,谢谢。 – mudasobwa

+0

谢谢@mudasobwa –

0
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"?>