0

I want to get from a string only the character: +,-,/,x
But this says - is a redundant character range.

String operacoes=texto.replaceAll("[^+?-?/?x]+"," ");

How can i make this work?

6
  • what is the value of texto ? texto = ? Commented Apr 16, 2015 at 14:29
  • it could be for example: 3 + 5 - 2 / 4 x 5. And after that operacoes will be: + - / x with spaces between. Commented Apr 16, 2015 at 14:31
  • Do you want output this "+- / x" ? Commented Apr 16, 2015 at 14:33
  • I'll give another example because i think you're mistaking. If texto=3 + 4 - 5 + 4. Then operacoes will be + - + Commented Apr 16, 2015 at 14:35
  • The problem is in the "-" Commented Apr 16, 2015 at 14:36

3 Answers 3

1

Just add \\ before - character. Because - character used in regex in various ways like [A-Z] [0- 9] etc. So to identify - you need to put \\ in java because single \ doesn't support in string in java.

    String texto="3 + 4 - 5 + 4";
    String operacoes=texto.replaceAll("[^+?\\-?/?x]+"," ");
    System.out.println(""+operacoes);
Sign up to request clarification or add additional context in comments.

Comments

0
String texto = "1+2-3/4x5";
String operacoes=texto.replaceAll("[^+?\\-?/?x]+"," ");
System.out.println(operacoes);

Produces the output

+ - / x 

Comments

0

You have to escape the minus sign using double backslash.

String operacoes=texto.replaceAll("[^+?\\-?/?x]+"," ");

Since the character - is used in regex

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.