English 中文(简体)
如何从红宝石的字符串中获取图形界面和值
原标题:How to retrieve a GUID and value from a string in ruby
  • 时间:2012-05-23 15:53:19
  •  标签:
  • ruby
  • regex

我在鲁比有这样一条绳子

word=0 id=891efc9a-2210-4beb-a19a-5e86b2f8a49f

我怎样才能从那个字符串得到单词和 ID 值?

最佳回答

这里的 s 方法将有效 - 将目标字符串分成符号, 由白空和等号字符( tokens=str.split (/[=]/) ) 和符号( Hash[*tokens] )组成, 并从中创建一个哈什(Hash[*tokens] ) 。 < a href=" "http://www.ruby-doc.org/corecore-1.9.3/Hash.html" rel="nofol" > 结果为 Hash , 其键是等号之前的符号, 其值是其后的符号 :

s =  word=0 id=891efc9a-2210-4beb-a19a-5e86b2f8a49f 
h = Hash[*s.split(/[= ]/)]
h # => {"word"=>"0", "id"=>"891efc9a-2210-4beb-a19a-5e86b2f8a49f"}
h[ word ] # => "0"
h[ id ] # => "891efc9a-2210-4beb-a19a-5e86b2f8a49f"

当然,如果你的“钥匙”或“价值”包含相同的符号或空格,它就会断裂,但对于你来说,它会有效。

问题回答
string="word=0 id=891efc9a-2210-4beb-a19a-5e86b2f8a49f"

word,id = string.match(/word=(.*) id=(.*)/).captures

这应该有帮助!

s = "word=0 id=891efc9a-2210-4beb-a19a-5e86b2f8a49f"

data = {}

s.scan(/(w+)(?==)=([^s]+)/).each do |pair|
  key, value = pair
  data[key.to_sym] = value
end

puts data.inspect    
#=> {"word"=>"0", "id"=>"891efc9a-2210-4beb-a19a-5e86b2f8a49f"}

puts data[:word]
#=> 0

puts data[:id]
#=> 891efc9a-2210-4beb-a19a-5e86b2f8a49f

我用简单的东西,比如:

str =  word=0 id=891efc9a-2210-4beb-a19a-5e86b2f8a49f 
word, id = str.scan(/=(S+)/).flatten # => ["0", "891efc9a-2210-4beb-a19a-5e86b2f8a49f"]

您想要的每一个值前都有 。 请使用此值的占位符 。 使用正则表达式中捕获的 < code> (...) 告诉 < code> scan 创建一个新的子数组, 所以 < code> blockten 将把子数组推回标准数组元素 :

 foo .scan(/(o)/) # => [["o"], ["o"]]
 foo .scan(/(o)/).flatten # => ["o", "o"]




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...