Nmaster88
Nmaster88

Reputation: 1585

Using method replaceall of String in Java

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?

Upvotes: 0

Views: 430

Answers (3)

Md. Nasir Uddin Bhuiyan
Md. Nasir Uddin Bhuiyan

Reputation: 1596

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

Upvotes: 1

qcGold
qcGold

Reputation: 200

You have to escape the minus sign using double backslash.

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

Since the character - is used in regex

Upvotes: 0

Justin L
Justin L

Reputation: 410

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

Produces the output

+ - / x 

Upvotes: 0

Related Questions