簡體   English   中英

在Ruby中解析字符串(Regexp?)

[英]Parsing a String in Ruby (Regexp?)

我有一個弦

Purchases 10384839,Purchases 10293900,Purchases 20101024

誰能幫我解析這個問題? 我嘗試使用StringScanner,但是我對正則表達式有點陌生(不是很多練習)。

如果我能把它分成

myarray[0] = {type => "Purchases", id="10384839"}
myarray[1] = {type => "Purchases", id="10293900"}
myarray[2] = {type => "Purchases", id="20101024"}

太棒了!

string = "Purchases 10384839,Purchases 10293900,Purchases 20101024"
string.scan(/(\w+)\s+(\d+)/).collect { |type, id| { :type => type, :id => id }}

您可以使用正則表達式來做到這一點,也可以只在Ruby中來做到這一點:

myarray = str.split(",").map { |el| 
    type, id = el.split(" ")
    {:type => type, :id => id } 
}

現在,您可以像“ myarray [0] [:type]”那樣解決它。

正則表達式不是必需的,也可能不是最清晰的方法。 在這種情況下,您需要的方法是split 這樣的事情會起作用

raw_string = "Purchases 10384839,Purchases 10293900,Purchases 20101024"
myarray = raw_string.split(',').collect do |item|
  type, id = item.split(' ', 2)
  { :type => type, :id => id }
end

可在以下位置找到split和collect方法的文檔:

可枚舉
String.split

這是一個irb會話:

dru$ irb
irb(main):001:0> x = "Purchases 10384839,Purchases 10293900,Purchases 20101024"
=> "Purchases 10384839,Purchases 10293900,Purchases 20101024"
irb(main):002:0> items = x.split ','
=> ["Purchases 10384839", "Purchases 10293900", "Purchases 20101024"]
irb(main):006:0> items.map { |item| parts = item.split ' '; { :type => parts[0], :id => parts[1] } }
=> [{:type=>"Purchases", :id=>"10384839"}, {:type=>"Purchases", :id=>"10293900"}, {:type=>"Purchases", :id=>"20101024"}]
irb(main):007:0> 

從本質上講,我會先將','分開。 然后,我將每個項目按空間拆分,並創建帶有各部分的哈希對象。 無需正則表達式。

   s = 'Purchases 10384839,Purchases 10293900,Purchases 20101024'
   myarray = s.split(',').map{|item| 
       item = item.split(' ')
       {:type => item[0], :id => item[1]} 
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM