简体   繁体   中英

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?

Just add \\\\ before - character. Because - character used in regex in various ways like [AZ] [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);

You have to escape the minus sign using double backslash.

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

Since the character - is used in regex

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

Produces the output

+ - / x 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM