我的字符串如下
case1:
str = "type="text/xsl" href="http://skdjf.sdjhshf/CDA0000=.xsl""
case2:
str = "href="http://skdjf.sdjhshf/CDA0000=.xsl" type="text/xsl""
我需要提取
之类的值 type -> text/xsl
href -> http://skdjf.sdjhshf/CDA0000=.xsl
这是我失败的正则表达。
str.match(/type="(.*)"/)[1]
#this works in second case
=>"text/xsl"
str.match(/http="(.*)"/)[1]
#this works in first case
=>"http://skdjf.sdjhshf/CDA0000=.xsl"
在失败情况下,整个字符串匹配。
有什么想法?
同意约翰·沃茨(John Watts)的评论。使用诺科吉里(Nokogiri)之类的东西来解析XML - 这很轻松。如果您仍然想坚持将正则解析,则可以做类似的事情:
str.split(' ').map{ |part| part.match( /(.+)="(.+)"/ )[1..2] }
您将获得以下结果:
> str = "type="text/xsl" href="http://skdjf.sdjhshf/CDA0000=.xsl""
=> "type="text/xsl" href="http://skdjf.sdjhshf/CDA0000=.xsl""
> str2 = "href="http://skdjf.sdjhshf/CDA0000=.xsl" type="text/xsl""
=> "href="http://skdjf.sdjhshf/CDA0000=.xsl" type="text/xsl""
> str.split(' ').map{ |part| part.match( /(.+)="(.+)"/ )[1..2] }
=> [["type", "text/xsl"], ["href", "http://skdjf.sdjhshf/CDA0000=.xsl"]]
> str2.split(' ').map{ |part| part.match( /(.+)="(.+)"/ )[1..2] }
=> [["href", "http://skdjf.sdjhshf/CDA0000=.xsl"], ["type", "text/xsl"]]
您可以放入哈希或wou想要的地方。
使用Nokogiri,您可以握住节点,然后在您的情况下执行类似node['href']
的事情。可能要容易得多。