如何解析表示算术运算序列的字符串? [英] How do I parse a string representing a sequence of arithmetic operations?

查看:63
本文介绍了如何解析表示算术运算序列的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个个人项目,我想接受如下所示的用户输入:

I am working on a personal project and I want to take in userinput that looks like this :

   1.0+2.5+3--4 

并将其格式化为以下格式:

and format it to something like this :

   1.0 + 2.5 + 3 - -4  

到目前为止,我正在使用.replace( +)到.replace( +)并对所有操作数执行此操作,但问题在于它使用户输入了以下内容:

so far I am using the .replace("+") to .replace(" + ") and doing that for all of the operands but the problem is it makes the user input into this:

  1.0 + 2.5 + 3 - - 4 

有没有一种方法可以使我带有负号。我想这样做,所以我可以将数字解析为双精度,并在以后加减。

Is there a way that I can make it with the negative signs. I want to do this so I could parse the numbers into doubles and add and subtract them later on.

我的代码:

  import java.util.Scanner;
   import java.util.regex.Matcher;
   import java.util.regex.Pattern;


public class StringMan {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    String check = "-a1 +a2 +       a3 +-a5";
    check  = check.replace("--", "+");
    System.out.println(check);
    Pattern pattern = Pattern.compile("\\s+");
      Matcher matcher = pattern.matcher(check);
      boolean expr = matcher.find();
      String str = matcher.replaceAll(" ");
      System.out.println(str);



}

   }

输出为:

   -a1 +a2 -       a3 +-a5
   -a1 +a2 - a3 +-a5

问题是我希望输出看起来像这样:
- a1 + a2-a3 + -a5

the problem is I want the output to look like this: -a1 + a2 - a3 + -a5

推荐答案

我建议使用正则表达式及其组功能。实际上,我将删除所有空格以使事情变得容易,将其排除在等式之外,这是一件少要处理的事情。显然,我建议您简化字符串,用 +替换-,用 *替换 * +,等等。

I would recommend using regular expressions and their "group" functionality. I would actually remove all whitespace to make things easier, take it out of the equation, one less thing to deal with. And obviously I would recommend simplifying the string, replacing "--" with "+", "*+" with "*" and so on.

现在可以使用了

Pattern firstPat = Pattern.compile("(((\\+|-)?)\\d+(.\\d+)?)");//for matching the first number, leading sign is optional
Pattern remainingPat = Pattern.compile("(\\+|-)(\\d+(.\\d+)?)");//for remaining numbers, leading sign is mandatory.
Pattern remainingPatWithExtOps = Pattern.compile("(\\*|/|\\+|-)(-?\\d+(.\\d+)?)");//for remaining numbers, accommodating multiply and divide with negative signs(positive signs should have been cleaned out)

Matcher match = firstPat.matcher(inputString);

现在您可以使用 match.find()方法。然后使用 match.group(1)获取符号/运算,然后使用 match.group(2)得到数字...

now you can iterate through the string using the match.find() method. and then use match.group(1) to get the sign/operation, and use match.group(2) to get the number...

所以...

Double firstnum;
boolean firstNumSigned = false;
if(match.find())
{
    firstNum = Double.parse(match.group(0));// Parsing handles possible sign in string. 
    //obv check for exceptions during this and double check group num
    String tmp = match.group(1);
    firstNumSigned = tmp.equals("+") || tmp.equals("-");
}
else
{//no match means the input was probably invalid....
    throw new IllegalArgumentException("What the heck were you thinking inputting that?!");
}
match = remainingPat.matcher(inputString);//use our other pattern for remaining numbers
if(firstNumSigned)
{
    match.find();//a signed first number will cause success here, we need to ignore this since we already got the first number
}
Double tmpRemaingingNum;
String operation;
while(match.find())
{
    operation = match.group(1);
    tmpRemainingNum = Double.parse(match.group(2));
    //Do what you want with these values now until match.find() returns false and you are done
}

PS:代码未经测试,对正则表达式非常有信心,但我不确定100%第一个模式的分组括号..可能需要试验

PS: code is not tested, im fairly confident of the regex, but I'm not 100% sure about the grouping brackets on the first pattern.. might need to experiment

这篇关于如何解析表示算术运算序列的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆