1 votes

Replacing characters in Java

I want to replace the java characters in a word:

Hol?a por -> Hol a 

private String escapaCaracter(String valor) {

String valorOk = " ";
try {
      valorOk = valor
                .replaceAll("/", "-")
                .replaceAll("\\\\", " ")
                .replaceAll("¿", " ")
                .replaceAll("?", " ")
                .replaceAll("#", " ")
                .replaceAll("<", " ")
                .replaceAll(">", " ")
                .replaceAll("[", " ")
                .replaceAll("]", " ")
                .replaceAll("{", " ")
                .replaceAll("}", " ");
} catch (Exception e) {
    if (s_log.isLoggable(Level.FINEST)) {
        s_log.log(Level.FINEST, "Ha fallado el escapaCaracter para el valor: " + valor);
    }
}

    return valorOk;
}

The problem is that even if it does not contain any of these characters, it fails ->

Value I was testing with -> pro

error ->

java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0
?
^

These characters correspond to some values that when a url is assembled could cause failures, I say this because of if anyone knows of more characters that could give failures, i.e. :

parameter1= hol/a ;

When mounting the url would appear -> http://...hol/a/param2... A blank space is intended to be left -> value = hol/a ; -> http://...hol a/param2...

1voto

Angabo Points 339

Use the following to replace all special characters at once:

To maintain the alphanumeric characters:

valorOk = valor.replaceAll("[^a-zA-Z0-9]+"," ");

For alphabetic characters only:

valorOk = valor.replaceAll("[^a-zA-Z]", "");

This saves many lines of code and does it all at once.

1voto

Evgeni Enchev Points 668

If it is a url it would be best to use java.net.URLEncoder.encode(urlString) .

Otherwise, if you are looking for the characters that can give you this error you should look at the code of java.util.regex.Pattern therein lies the error Dangling meta character . Just as a preview - the characters that will give you an error are ?, *, + . Apart from these there are a few others that are not suitable for patterns.

I insist, if it is to avoid problems in url better URLEncoder .

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X