javascript - 用于拆分数学表达式的正则表达式
问题描述
我有一个字符串格式的 for "1+2-4*5+0.9+10.5+..." 表达式,我想将它拆分为一个数组,以便表达式中从第二个开始的每个数字都与之前的数学运算。(即[“+2”,“-4”,“ 5,...])。我尝试使用正则表达式/[-+*/][0-9]+|[-+*/][.0-9]+|[-+*/][0-9]+\.[0-9]+/g
并成功吐出整数,但未捕获小数点后的任何内容(请参阅附加的代码片段)。如何修改正则表达式的最后一部分(即 [-+ /][0-9]+.[0-9]+),使其适用于所有小数部分?
expression="5-0.23+.65+.9+0.5+10.5";
const numArr=expression.match(/[-+*/][0-9]+|[-+*/][.0-9]+|[-+*/][0-9]+\.[0-9]+/g);
console.log(numArr);
console.log("As you can see the regex is failing to capture decimals unless they start with a period(.)")
解决方案
您可以在 split() 方法中使用正则表达式:
expression="5-0.23+.65+.9+0.5+10.5";
const numArr = expression.split(/(?=\-)|(?=\+)/g)
console.log(numArr)
推荐阅读
- ios - 为什么当我点击文本字段时工具栏不显示?
- excel - 从网站中选择下拉菜单
- javascript - React 向 Node 发出 Get 请求的问题(快递)
- sql - 字段与联接中的 SQL 性能子查询
- sdn - 从交换机获取流信息并将信息复制到 csv 文件中(Ryu 控制器)
- javascript - Bootstrap popper 对我的生活不起作用
- encryption - 解密 Word 文档,了解其部分内容
- javascript - 如何从 yupgrid 中删除或禁用添加行和删除行操作按钮?
- python - 如何从 PHP exec 调用 python
- python - 如何解决给定节点连接、节点值和查询的树差异问题?(Dijkstra 算法)