我正在尝试查找并返回字符串中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
我正在尝试查找并返回字符串中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
我会做这样的:
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
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
你可以这样做:
message.split(' ')[1].scan(/\d/)
或者这样:
message.gsub(/[^0-9]/, '')
或者你可以使用一个循环:
message.each_char{ |c| if c.ord<11 or c.ord>0 }
这只看在邮件中的第二个单词 –
噢..只要做c.ord> = 0 ...和[0] .scan(/ \ d /)以及.. – user2975403
message.split.find { |string| (0..10).include?(string =~ /\A\d+\z/) }
这实际上并不是'我想删除它,但你不得不接受它 –
试试这个: -
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"]
当我尝试“1000非常好”时,它返回了1000个 – grabury
@spuggy现在它赢得了' t匹配1000。 –
你可以试试这个:
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
)周围的正则表达式,以便它不匹配的文字贴任何数字。
就这么简单message[/\b([0-9]|10)\b/]
我试图提取比分 – grabury
基于什么spuggy表明他们尝试了,我想他们希望回到“8”或“10”,并没有提出任何东西。另外,你的解决方案将匹配诸如“xyz8 out of gem”(它会放入“xyz8”)。 –
是的。我现在发现了这个错误。 :( – Emu