【问题标题】:Ruby regular expression to extract key values用于提取键值的 Ruby 正则表达式
【发布时间】:2012-10-25 18:46:17
【问题描述】:

我有如下字符串

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"

在失败的情况下,整个字符串都匹配。

有什么想法吗?

【问题讨论】:

  • 看起来您正在解析 XML。通常,使用为此目的设计的库是一个好主意。您不能或不会这样做有什么特别的原因吗?
  • 是的。我正在使用 Nokogiri。但是 Nokogiri 只为样式表节点提供字符串。所以只有我在寻找正则表达式。
  • Nokogiri 什么都做,不只是 css。
  • @oldergod 请看一下这个问题。以便您了解问题所在。 stackoverflow.com/questions/13066231/…

标签: ruby regex


【解决方案1】:

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

你可以把它放在一个散列或任何你想要的地方。

使用 nokogiri,您可以获取一个节点,然后在您的情况下执行node['href'] 之类的操作。可能要容易得多。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-31
  • 1970-01-01
  • 2021-11-18
  • 2019-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多