在字符串中的每个一两个字符后插入空格 [英] Insert space after every one or two characters in string
问题描述
我需要编写代码来更正用户输入.输入是中缀形式的数学表达式.为了使我的计算正确,我需要将每个操作数与运算符隔开.
I need to write code to correct user input. The input is a mathematical expression in infix form. In order for my calculations to be correct, i need each operand spaced away from the operator.
能否请您帮我写一个方法,该方法将提供以下预期结果.
Can you please help me write a method that will provide the following expected results.
预期输入:13 * 21-5 + 33预期输出:13 * 21-5 + 33
Expected input: 13*21-5+33 Expected Output: 13 * 21 - 5 + 33
我已经完成的研究:我只能找出如何在字符串的每个字符之间添加空格,而这对于计算具有两位数值的表达式将不起作用.即:1 3 * 2 1-5 + 3 3.
Research I have done: I could only find out how to add spaces between every character in the string and that will not work for calculating expressions with double digit values. Ie: 1 3 * 2 1 - 5 + 3 3. How to insert Space after every Character of an existing String in Java?
谢谢
推荐答案
此解决方案将每个运算符周围的空格归一化.
This solution normalizes the whitespace around each operator.
return expr.replaceAll("(?<=\\d)\\s*([-+/*])\\s*(?=\\d)", " $1 ");
这篇关于在字符串中的每个一两个字符后插入空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!