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 likeO_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
相关产品推荐
相关产品推荐

