【问题标题】:Parsing a String in Ruby (Regexp?)在 Ruby 中解析字符串(正则表达式?)
【发布时间】:2009-07-07 20:30:57
【问题描述】:

我有一个字符串

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

那太棒了!

【问题讨论】:

    标签: ruby regex


    【解决方案1】:
    string = "Purchases 10384839,Purchases 10293900,Purchases 20101024"
    string.scan(/(\w+)\s+(\d+)/).collect { |type, id| { :type => type, :id => id }}
    

    【讨论】:

    • Rutger 的解决方案没有任何问题,但对我来说这感觉更像 Ruby。 +1
    • 这个答案救了我
    【解决方案2】:

    你可以用正则表达式来做,或者只用 Ruby 做:

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

    现在您可以像 'myarray[0][:type]' 一样处理它。

    【讨论】:

      【解决方案3】:

      正则表达式不是必需的,也可能不是最清晰的方法。在这种情况下您需要的方法是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 方法的文档可以在这里找到:

      Enumerable.collect
      String.split

      【讨论】:

        【解决方案4】:

        这是一个 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> 
        

        基本上,我会先拆分“,”。然后我会按空格分割每个项目并用这些部分创建散列对象。不需要正则表达式。

        【讨论】:

        • 不需要正则表达式,但也许推荐正则表达式?我想知道哪个会更有效。
        【解决方案5】:
           s = 'Purchases 10384839,Purchases 10293900,Purchases 20101024'
           myarray = s.split(',').map{|item| 
               item = item.split(' ')
               {:type => item[0], :id => item[1]} 
           }
        

        【讨论】:

        • 问个简单的问题:mapcollect 有什么区别?
        猜你喜欢
        • 1970-01-01
        • 2023-03-06
        • 2016-04-29
        • 2012-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多