2016-03-18 88 views
1

試圖用ruby編程計算器,我想把所有東西都放到一個數組中,這樣我就可以用gsub輸出單詞爲數學符號。拆分空間和非數字...包括非數字分隔符,不包括空格分隔符

answer ||= 0 
puts "CALCULATE" 
puts "#{answer}" 
input = gets.chomp.split(/([\s\D])/) 

# for test 
puts "response #{input}" 
puts "asdf" unless input.is_a? Array 
puts "qwer array inputs: #{input.length}" 

研究它永遠,很多很多的感謝

尋找

8*15 => ["8", "*", "15"] 
eight times 15 => ["eight", "times", "15"] 
8 divided by 15 => ["8", "divided", "by", "15"] 
+0

也許'split(/ [\ s \ b] /)' – Stefan

回答

0

您可以使用

re = /\s+|([^\d\s]+)/ 
puts "8*15".split(re).reject { |c| c.empty? } 

IDEONE demo

\s+匹配1個或多個空白符號(並且它們將被刪除,因爲我們不捕獲此子模式)並且([^\d\s]+)將會匹配並且捕獲 1+符號,而不是數字和空格,並且將在捕獲後輸出。

隨着.reject { |c| c.empty? },我們擺脫了結果數組內的空元素。

+0

瘋了。所以我正在準備在一個或多個空白處分割,或者在除數字/空格之外的任何其他位置(或其他字符或%* - /類型)之外的其他位置進行分割,並捕獲數字/空白以外的其他位置。爲什麼不使用\ D \ S?非常感謝你 – daveasdf

+0

你不能僅僅使用\ D,因爲它會在每個非數字上分割(如果你添加\ S?比在分割過程中會消耗一個或零非空白空間)。 –

+0

[^ \ T \ s] + .......我可以把任何簡寫在T是,它會工作。 – daveasdf

0

Wiktor的的回答是不錯的,但這裏是爲了完整起見一種替代方案:

expr = /[\S&&\D]+|\d+/ 

p "8*15".scan(expr) 
# => ["8", "*", "15"] 

p "eight times 15".scan(expr) 
# => ["eight", "times", "15"] 

p "eight divided by 15".scan(expr) 
# => ["eight", "divided", "by", "15"] 

而是分裂字符串,這裏採用String#scan返回字符串的匹配部分。這裏的解剖正則表達式:

expr =/
    [\S&&\D]+ # One or more characters that is neither whitespace nor a digit 
    |   # ...or... 
    \d+  # One or more digits 
/x 

在情況下,它不熟悉的,&&character class是交集操作符。 \S是所有非空白字符的集合,\D是所有非數字字符的集合,因此[\S&&\D]匹配任何既不是空白也不是數字的字符。

相關問題