2011-12-31 65 views
0

我有一个字符串像“1 first - 22 second - 7 third”,我需要获得每个项目的整数值。例如,如果我想获得第三个值,他们将返回7如何在字符串之前使用regex整数匹配?

我试着用这个代码,但它不工作:

item = detail.scan(/(-)\d(second.*)/) 
+0

你的意思是第三个数字每一次?字符串中的任何整数? – fge 2011-12-31 18:31:42

回答

1

scan是伟大的一些数据,但如果你要确保你不只是收集垃圾数据你可能需要的东西为此更有条理。记录分隔符“ - ”上的快速分割可确保在从项目中提取整数之前,每个项目都与其他项目分开。

your_string = "1 first - 22 second - 7 third" 
items = your_string.split ' - ' 
numbers = items.map { |item| item[/\d+/].to_i } 

#=> [1, 22, 7] 
0
"1 first - 22 second - 7 third".split(" - ").map(&:to_i) 
0

使用正确的正则表达式:

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 
相关问题