Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

javascript - Regex for a splitting a mathematical expression

I have an expression of for "1+2-4*5+0.9+10.5+..." in string format and I want to split it into an array so that every number from the second one onwards in the expression is paired with the math operation before it. (i.e. ["+2","-4","5,...]). I have attempted using regex /[-+*/][0-9]+|[-+*/][.0-9]+|[-+*/][0-9]+.[0-9]+/g and am succeeding in spitting whole numbers but anything after a decimal point is not captured (see attached code snippet). How do I modify the last part of the regex (i.e. [-+/][0-9]+.[0-9]+) so that it works properly for all decimal fraction?

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(.)")
question from:https://stackoverflow.com/questions/65941511/regex-for-a-splitting-a-mathematical-expression

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a regex inside a split() method:

expression="5-0.23+.65+.9+0.5+10.5";
const numArr = expression.split(/(?=-)|(?=+)/g)
console.log(numArr)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...