You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中用正则分割数学表达式字符串遇空元素问题求助

Fix for Tokenizing Math Expression

The empty strings in your split result come from split() capturing the gaps between adjacent matched characters (like between - and () or before the first match. Instead of fighting with split(), using match() is a more straightforward way to get exactly the tokens you want.

Here's the regex to use with match():

const formula = '1+2-(0.67*2)/2%2=O_AnnualSalary';
const tokens = formula.match(/[a-zA-Z_][a-zA-Z0-9_]+|[0-9]|[+\-*/%()=.]/g);

What this regex does:

  • [a-zA-Z_][a-zA-Z0-9_]+: Grabs identifiers like O_AnnualSalary (starts with letter/underscore, followed by letters, numbers, or underscores) as single tokens.
  • [0-9]: Captures individual digits (0-9) as separate tokens.
  • [+\-*/%()=.]: Matches each operator, parenthesis, decimal point, or equals sign as its own token.

Running this will give you your expected output:

['1', '+', '2', '-', '(', '0', '.', '6', '7', '*', '2', ')', '/', '2', '%', '2', '=', 'O_AnnualSalary']

If you want to stick with split():

Just filter out the empty strings after splitting:

const tokens = this.createdFormula.split(/([?=+-*/%,()])/).filter(token => token !== '');

This removes the unwanted empty entries while keeping all valid tokens.

内容的提问来源于stack exchange,提问作者Vaibhav Mandlik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 22:40:23