2

私は以下のような文字列を持っています

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"

失敗した場合、文字列全体が一致します。

何か案が?

4

1 に答える 1

3

ジョン・ワッツのコメントに同意します。XML を解析するには、nokogiri のようなものを使用します。簡単です。それでも正規表現の解析に固執したい場合は、次のようにすることができます。

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"]] 

ハッシュまたはどこにでも置くことができます。

nokogiri を使用すると、ノードを取得してnode['href']、あなたの場合のようなことを行うことができます。おそらくはるかに簡単です。

于 2012-10-25T10:46:17.440 に答える