我有一個字符串像「1 first - 22 second - 7 third
」,我需要獲得每個項目的整數值。例如,如果我想獲得第三個值,他們將返回7
。如何在字符串之前使用regex整數匹配?
我試着用這個代碼,但它不工作:
item = detail.scan(/(-)\d(second.*)/)
我有一個字符串像「1 first - 22 second - 7 third
」,我需要獲得每個項目的整數值。例如,如果我想獲得第三個值,他們將返回7
。如何在字符串之前使用regex整數匹配?
我試着用這個代碼,但它不工作:
item = detail.scan(/(-)\d(second.*)/)
scan
是偉大的一些數據,但如果你要確保你不只是收集垃圾數據你可能需要的東西爲此更有條理。記錄分隔符「 - 」上的快速分割可確保在從項目中提取整數之前,每個項目都與其他項目分開。
your_string = "1 first - 22 second - 7 third"
items = your_string.split ' - '
numbers = items.map { |item| item[/\d+/].to_i }
#=> [1, 22, 7]
"1 first - 22 second - 7 third".split(" - ").map(&:to_i)
使用正確的正則表達式:
str = "1 first - 22 second - 7 third"
str.scan(/\d+/).map{ |i| i.to_i } # => [1, 22, 7]
如果您需要訪問某個特定值時使用的索引返回值:
str.scan(/\d+/).map{ |i| i.to_i }[-1] # => 7
str.scan(/\d+/).map{ |i| i.to_i }[2] # => 7
str.scan(/\d+/).map{ |i| i.to_i }.last # => 7
你的意思是第三個數字每一次?字符串中的任何整數? – fge 2011-12-31 18:31:42