如何从字符串中提取数字

时间:2014-03-14 06:43:14

标签: ruby

我正在寻找并在字符串中返回0到10之间的分数。 消息示例

"Toni gets 9"
"8 for Sam"
"10 is a reasonable score for Jed"

这是我尝试过的:

message.split.find do |score|
 (0..10).include? score.to_i
end

7 个答案:

答案 0 :(得分:2)

我这样做:

regexp = /\b(?:10|[0-9])\b/

'Toni gets 9'[regexp]
# => "9"

'8 for Sam'[regexp]
# => "8"

'10 is a reasonable score for Jed'[regexp]
# => "10"

'11 is my score'[regexp]
# => nil

'01 is your score'[regexp]
# => nil

'1000 is no score'[regexp]
# => nil

答案 1 :(得分:1)

message.split.find { |string| (0..10).include?(string =~ /\A\d+\z/) }

答案 2 :(得分:0)

a = ["8 out of gem", "ruby got 10", "ali receives 13 marks"]

a.each do |i|
  if ((i =~ /\d/) > -1 && (i =~ /\d/) < 11)
    puts i
  end

end

<强>输出:

8 out of gem
ruby got 10

答案 3 :(得分:0)

你可以这样做:

message.split(' ')[1].scan(/\d/)

或者这个:

message.gsub(/[^0-9]/, '')

或者您可以使用循环:

message.each_char{ |c| if c.ord<11 or c.ord>0 }

答案 4 :(得分:0)

试试这个: -

messages = ["Toni gets 9",
"8 for Sam",
"10 is a reasonable score for Jed",]

irb> messages.collect{|msg| msg.split.find{|str| str.match /\b^(10|[0-9])\b/}}
 => ["9", "8", "10"] 

答案 5 :(得分:0)

你可以尝试这个:

input = [ "0 Toni", "Toni gets 9", "8 for Sam", "10 is", "11 is" ]
input.each do |sentence|
  if(sentence =~ /\b([0-9]|10)\b/)
    puts sentence
  end
end

我在正则表达式周围使用了单词边界(\b),因此它与任何粘贴在文本中的数字都不匹配。

答案 6 :(得分:0)

它就像message[/\b([0-9]|10)\b/]

一样简单