regex - 使用正则表达式将数学公式拆分为数组
问题描述
我正在寻找一个平面字符串公式并将其拆分为一个数组,根据几个因素进行划分。在括号周围有点卡住并寻求帮助。
我一直在使用正则表达式扫描和一些过滤器来尝试获取结果数组。
我目前的测试是这样的:
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
使用以下代码,我可以让前半部分顺利通过:
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
我尝试修改pattern
以接受括号匹配器:
pattern = (\(|\))|(?:(\ (\*\ |\+\ |\-\ |\\\ |\=\ )\S*))|(\S*)
但这仅捕获公式开头的括号。
解决方案
我最终做了以下似乎可行的事情:
split_paren(arr)
在 .结尾处添加了对新方法的调用split_algo
。
def split_paren(algo_arr)
pattern = /Round\(\d*\)/
arr = []
algo_arr.each do |step|
f = step.split(/(\(|\))/) unless step =~ pattern
f.delete('') if f.class == Array
f.nil? ? arr << step : f.each{|s| arr << s.strip}
end
arr
end
如果有人想以更好的方式回应,请随时回应。否则,我将接受我的回答并在此结束问题。
推荐阅读
- android - 无法解析符号 AppCompatActivity
- c++ - 当我尝试删除指针时我的程序崩溃了
- c++ - 从本机 C++ 结构构建时是否可以优化 flatbuffers 序列化?
- php - 为什么我的 crontab 不在服务器中运行我的电报机器人 php 代码?
- excel - 在宏中查找excel表的最后一行和最后一列
- json - MongoDB查询过滤对象数组和格式返回对象
- r - 如何在 R 中修复大型数据框
- reactjs - 向 Redux 存储添加嵌套数组项时未定义 this.props.onPress(row)
- python - 如何在字典中返回具有相同长度的值?
- java - 肥皂请求java中缺少标头