Replace in the inverted bar " " in java

Asked

Viewed 3,159 times

1

I need to take the backslash (" ") of a string, I’ve searched in several ways, but none of it worked.

Please help me, follow code.

f = new File(path,prefix + "_" + dataArq + "_" + pesquisa.replaceAll("\\", "") + ".txt");
System.out.println(pesquisa);

I’m trying to replace the string pesquisa to take out the Backslash that is coming in the file generation.

  • 2

    have tried with \\ ?

  • Ever tried to use replace in place of replaceAll?

1 answer

6


It occurs that the first parameter of the method replaceAll is a regular expression. Therefore, there are two alternatives:

  • Use the correct regular expression. With "\\\\" in the source code, each \\ is an escape sequence for the character \, so that the contents of the string that the compiler will see will be \\. This as regular expression, is the escape sequence for the character \ alone.

  • Do not use regular expressions and use method replace instead of replaceAll.

Here is a test that uses both approaches:

class Teste {
    public static void main(String[] args) {
        String teste1 = "a\\b\\c\\d\\e";
        System.out.println(teste1);
        String teste2 = teste1.replace("\\", "");
        System.out.println(teste2);
        String teste3 = teste1.replaceAll("\\\\", "");
        System.out.println(teste3);
    }
}

That’s his way out:

a\b\c\d\e
abcde
abcde

See here working on ideone.

Ah, and remember that strings are immutable, so if you do this:

String pesquisa = "\\uma\\string\\cheia\\de\\barras\\invertidas\\";
f = new File(path,prefix + "_" + dataArq + "_" + pesquisa.replaceAll("\\\\", "") + ".txt");
System.out.println(pesquisa);

The original string full of inverted bars is the one that will appear on System.out.println. On the other hand, if you do this:

String pesquisa = "\\uma\\string\\cheia\\de\\barras\\invertidas\\";
String pesquisa2 = pesquisa.replaceAll("\\\\", ""); // Ou .replace("\\", "");
f = new File(path,prefix + "_" + dataArq + "_" + pesquisa2 + ".txt");
System.out.println(pesquisa2); // É "pesquisa2"! Não é "pesquisa"!

There will be printed the result without the inverted bars.

  • I think replaceAll is the need for it, because the dates are the folders and the search is the file, but I have already left +1 because it has solved the problem in one way or another

  • @Guilhermenascimento I complemented the answer. I think he also did not notice that he is giving System.out.println in the wrong thing.

  • I think this 100% :)

  • Thanks, it all worked out.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.