1

It's my part of java program for project.

String ops="";
String input="1+3-4+(7/8)+cos(sin(50)+2)/2+tan(90)*e^(5+26-4/1*2)";
input=input.replaceAll("cos", "c").replaceAll("sin", "s").replaceAll("tan", "t").replace("e", "2.718");
//System.out.println(input);
Pattern pattern=Pattern.compile("[+-/*()cst^]");
Matcher matcher= pattern.matcher(input);
while (matcher.find()) {ops+=matcher.group();}
System.out.println(ops);

Here I am just reading the input and giving output of +,-,/,*,(,),c,s & t present in it. The output ops should return +-+(/)+c(s()+)/+t()*^(+-/*) while it's returning +-+(/)+c(s()+)/+t()*.^(+-/*).Help me understand the reason please.

assylias
  • 321,522
  • 82
  • 660
  • 783
The_ehT
  • 1,202
  • 17
  • 32

1 Answers1

4

- is used for a range, so +-/ includes all characters between + and / (in the ascii table), i.e. ,-./. To solve the issue you can place the - in first position:

Pattern.compile("[-+/*()cst^]");

Or you could also escape it. More about this: How to match hyphens with Regular Expression?

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783