在Ruby中从string中提取数字
我正在使用这个代码:
s = line.match( /ABCD(\d{4})/ ).values_at( 1 )[0] 从string中提取数字,如:
 ABCD1234 ABCD1235 ABCD1236 
等等
它的工作原理,但我不知道还有什么其他的select,我必须在Ruby?
我的代码:
 ids = [] someBigString.lines.each {|line| ids << line.match( /ABCD(\d{4})/ ).values_at( 1 )[0] } 
	
 a.map {|x| x[/\d+/]} 
根据http://www.ruby-forum.com/topic/125709有许多Ruby方法;
-  line.scan(/\d/).join('')
-  line.gsub(/[^0-9]/, '')
-  line.gsub(/[^\d]/, '')
-  line.tr("^0-9", '')
-  line.delete("^0-9")
-  line.split(/[^\d]/).join
-  line.gsub(/\D/, '')
尝试每个你的控制台。
还要检查该post中的基准报告。
还有更简单的解决scheme
 line.scan(/\d+/).first 
另一个解决scheme可能是写:
 myString = "sami103" myString.each_char{ |c| myString.delete!(c) if c.ord<48 or c.ord>57 } #In this case, we are deleting all characters that do not represent numbers. 
现在,如果你input
 myNumber = myString.to_i #or myString.to_f 
这应该返回一个
 your_input = "abc1cd2" your_input.split(//).map {|x| x[/\d+/]}.compact.join("").to_i 
这应该工作。
要从string中提取数字部分,请使用以下命令:
 str = 'abcd1234' /\d+/.match(str).try(:[], 0) 
 它应该返回1234