我正在嘗試查找並返回字符串中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