Removing replaceAll("[().- "]")

Asked

Viewed 549 times

0

I’m using the openJDK1.7, I’m in need of help.

String[] vetor = {"\"Jui.ce \"", "j-90.0", "Abobr.e-u"};

for(int = 0; i < vetor.length; i++)
   vetor[i].replaceAll("[()-.\"]", "");

The above code among others is not giving problem but is not working, when I apply to remove one at a time. I wanted to remove at once. Where am I missing?

2 answers

1


The class String in Java is immutable. This means that its value does not change after its creation. When you call the method replaceAll(String regex, String replacement), a new String is returned with the result and the String original remains unchanged. Try this way:

String[] vetor = {"\"Jui.ce \"", "j-90.0", "Abobr.e-u"};
String[] resultado = new String[vetor.length];

for(int i = 0; i < vetor.length; i++)
   resultado[i] = vetor[i].replaceAll("[()-.\"]", "");

for(String s : resultado)
    System.out.println(s);
  • Good Night, Felipe! Thank you... it worked https://goo.gl/oVez3R Online IDE just to share with you how it works.

  • good (+1). A small detail: the character - in character sets needs to be protected: [)-.] = [)*+,-]

0

Try it this way

  • "when I apply to remove one at a time the right", take and assemble it, as follows:
  • [ "value-1"|"value-2"|"value-3"] test and see if it is right.
  • Detail this can be much slower than removing one by one
  • Put the result there, I couldn’t test it here.

No pull, you have programming error, not regular expression parsing.

public class ManipulandoString{
  public static void main(String[] args){
        String[] vetor = {"\"Jui.ce \"", "j-90.0", "Abobr.e-u"};
        String[] result = new String[3];
        for(int i=0; i <vetor.length; i++)
            result[i]=vetor[i].replaceAll("[.|\"|\\(|\\)|-]", "");
        for(int i = 0; i < vetor.length; i++)
         System.out.println(result[i]);
    }

}

look at the result this, I tried to update in the test, I think it’s there, if not just copy from here to there.

  • Marcelo, Boa Noite! for(int i =0; i < vector.length; i++) vector[i]. replaceAll("| (| )|-|.", "");

  • https://goo.gl/t0fXuW As promised running but not modified, I will try Felipe Marinho’s tip

  • See I updated the answer

Browser other questions tagged

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