我如何获得子串?

时间:2017-05-09 14:20:44

标签: ruby-on-rails ruby web

如何获取字符串的子字符串:

[{
  "ProductId"=>198, 
  "AttributesXml"=>"<Attributes><ProductAttribute ID=\"590\"><ProductAttributeValue><Value>1691</Value></ProductAttributeValue></ProductAttribute></Attributes>",   
  "StockQuantity"=>1, 
  "AllowOutOfStockOrders"=>false,
  "Sku"=>nil, 
  "ManufacturerPartNumber"=>nil, 
  "Gtin"=>nil, 
  "OverriddenPrice"=>nil, 
  "NotifyAdminForQuantityBelow"=>1, "Id"=>1756
  },

我只想要"ProductAtrribute ID": 590的值。只有数字。 我查看了ruby文档,但我找不到解决方案。

3 个答案:

答案 0 :(得分:3)

标签有rails,如果你在rails中,那么你可以利用nokogiri gem来处理解析AttributesXml部分:

require 'nokogiri'

array = [{"ProductId"=>198, "AttributesXml"=>"<Attributes><ProductAttribute
 ID=\"590\"><ProductAttributeValue><Value>1691</Value>
 </ProductAttributeValue></ProductAttribute></Attributes>",
 "StockQuantity"=>1, "AllowOutOfStockOrders"=>false,"Sku"=>nil,
 "ManufacturerPartNumber"=>nil, "Gtin"=>nil, "OverriddenPrice"=>nil,
 "NotifyAdminForQuantityBelow"=>1, "Id"=>1756}]

array.each do |item|
  doc = Nokogiri::XML(item['AttributesXml'])
  puts doc.xpath("//ProductAttribute").attribute('ID')
end
=> 590

答案 1 :(得分:1)

我会用:

require 'nokogiri'

foo = [
  {
    "ProductId"=>198, 
    "AttributesXml"=>"<Attributes><ProductAttribute ID=\"590\"><ProductAttributeValue><Value>1691</Value></ProductAttributeValue></ProductAttribute></Attributes>",   
    "StockQuantity"=>1, 
    "AllowOutOfStockOrders"=>false,
    "Sku"=>nil, 
    "ManufacturerPartNumber"=>nil, 
    "Gtin"=>nil, 
    "OverriddenPrice"=>nil, 
    "NotifyAdminForQuantityBelow"=>1, "Id"=>1756
  },
]

foo.map { |hash|
  Nokogiri::XML(hash['AttributesXml']).at('ProductAttribute')['ID']
}
# => ["590"]

它将返回数组中所有哈希值中所有<ProductAttribute>个节点的ID。

答案 2 :(得分:0)

您可以使用scan

array = [{"ProductId"=>198, "AttributesXml"=>"<Attributes>
  <ProductAttribute  
  ID=\"590\"><ProductAttributeValue><Value>1691</Value>
  </ProductAttributeValue></ProductAttribute></Attributes>",   
  "StockQuantity"=>1, "AllowOutOfStockOrders"=>false,""Sku"=>nil, 
  "ManufacturerPartNumber"=>nil, "Gtin"=>nil, "OverriddenPrice"=>nil, 
  "NotifyAdminForQuantityBelow"=>1, "Id"=>1756},.. ]

array.each do |hash| 
  hash["AttributesXml"].scan(/ProductAttribute\s+ID=\"(\d+)\"/).flatten
  #=> ["590"]
  # This will return matched values
end