如果字符串结尾和指定字符之间没有出现小数,则将十进制数添加到字符串

时间:2017-10-16 10:40:12

标签: java regex string

我正在编写一个基本的计算器程序并实现小数。在尝试设计一种将十进制附加到操作数的方法时,我遇到了十进制重复的问题。

"5.5.5" // shouldn't be possible, ignore second . addition
"5.5 + 5.5" or "5 + 5.5" // wonderful!

我有一些像这样的代码:

String expression = "";
...
//various methods to append numbers, operators, etc to string
...
addDecimal() {
    if (expression.equals("")) {
        expression += "0."; // if no operand, assume it's 0-point-something
    } else {
        if(/* some condition */) {
            expression += ".";
            //note it is appending a decimal to the end of the expression
            //ie at the end of the rightmost operand
        }
    }
}

运算符为+-*/。对我正在尝试做的更具说明性的描述是:

check string if it contains a decimal
    if not, addDecimal()
    if so, split string by operators above, look at the rightmost operand; does it contain a decimal?
        if not, addDecimal()
        if so, do nothing

例如

expression = "2";
addDecimal(); //expression is now "2."
//append decimal to only operand

expression = "5.5 + 4";
addDecimal(); //expression is now "5.5 + 4."
//append a decimal to rightmost operand

expression = "7.5";
addDecimal(); //expression is now "7.5"
//if an operand contains a decimal already, it cannot have another

expression = "2 + 5";
addDecimal(); //expression is now "2 + 5."
//note the decimal was only appended to the rightmost operand
//ignoring the leftmost operand

一致规则是十进制只附加到最右边的操作数,而不是附加到表达式中的所有操作数。

2 个答案:

答案 0 :(得分:0)

您可以使用此基于外观的正则表达式进行替换:

Item_B

RegEx Demo

RegEx分手:

  • str = str.replaceAll("(?<!\\.)\\b\\d+\\b(?!\\.)(?!.*\\d)", "$0."); :断言我们在前一个位置没有点
  • (?<!\\.):将一个或多个数字与字边界匹配
  • \\b\\d+\\b:断言我们没有前方点
  • (?!\\.):确保我们是最合适的操作数

答案 1 :(得分:-1)

您可以使用String.split

<强> e.g。

String[] splitExpression = expression.split(".");
if(splitExpression.length > 2){
    expression = splitExpression[0] + "." + splitExpression[1];
}
else {
    // Either a valid decimal or no decimal number at all
}