I'm looking to get a flat string formula and split it into an array, divided based on a few factors. Getting a little stuck around parenthesis and looking for assistance.
I've been using a regex scan plus a few filters to try and get the resulting array.
My current tests are such:
describe 'split algorithm' do
it 'can split a flat algorithm' do
algo = 'ABC * DEF * GHI Round(3) = JKL * MNO * PQR Round(0) = SAVE'
actual = split_algo(algo)
expected = ['ABC', '* DEF', '* GHI', 'Round(3)', '= JKL', '* MNO', '* PQR', 'Round(0)', '= SAVE']
expect(actual).to eq expected
end
it 'can split an algorithm with parenthesis' do
algo = '(ABC + DEF + (GHI * JKL)) - ((MNO + PQR + (STU * VWX)) * YZ) Round(0) + SUM(AAA) = SAVE'
actual = split_algo(algo)
expected = ['(', 'ABC', '+ DEF', '+', '(', 'GHI', '* JKL', ')', ')', '-', '(', '(', 'MNO', '+ PQR', '+', '(', 'STU', '* VWX', ')', ')', '* YZ', ')', 'Round(0)', '+ SUM', '(', 'AAA', ')', '= SAVE']
expect(actual).to eq expected
end
end
With the following code, I can get the first half to pass just fine:
def split_algo(algorithm)
pattern = /(?:(\ (\*\ |\+\ |\-\ |\\\ |\=\ )\S*))|(\S*)/
matches = algorithm.scan(pattern)
matches.each_with_index { |match, index| matches[index]=match.compact }
arr = []
matches.each do |match|
arr << match.max_by(&:length).strip
end
arr.delete('')
arr
end
I've tried modifying pattern
to accept a parenthesis matcher as such:
pattern = (\(|\))|(?:(\ (\*\ |\+\ |\-\ |\\\ |\=\ )\S*))|(\S*)
But that only captures the parenthesis at the beginning of the formula.