开发者

How do I parse a string representing a sequence of arithmetic operations?

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  

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.

my code for it :

  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.p开发者_运维技巧rintln(str);



}

   }

output is:

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

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


In this specific case, you can handle -- by just replacing them with +:

  1. Take input as a string from the user
  2. Remove all white space
  3. Replace all -- with +
  4. Continue parsing as desired


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.

now you can use a regex on your cleaned up string.

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);

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...

So...

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: 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


Start by replacing -- with +, which is mathematically equivalent. Or start by replacing -- with - -, which would keep - and 4 together.


Check this , Read both strings and integers in between operators like '*,--,-,+" We can read both integers and characters.

public static void main(String[] args) {
    // TODO Auto-generated method stub
    final Pattern remainingPatWithExt=Pattern.compile("(\\p{L}\\p{M}*)[\\p{L}\\p{M}0-9^\\-.-?_+-=<>!;]*");
    String check = "a1+a2+--a7+    a3 +-a5";

      Matcher matcher = remainingPatWithExt.matcher(check);
      while( matcher.find())
      {
          System.out.println(matcher.group()); 
            //use  matcher.group(0) or matcher.group(1)
      }

}

output

a1 a2 a7 a3 a5

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜