Home > Mobile >  How to remove "[ ]" in the code given below? Expected output is "pollTimestamp"
How to remove "[ ]" in the code given below? Expected output is "pollTimestamp"

Time:10-19

public class HelloWorld{

     public static void main(String []args){
        String a = "[pollTimestamp]";
        a.replaceAll("[^a-zA-Z0-9]","");
        System.out.print(a);
     }
}

CodePudding user response:

If you want to stick with your current approach, you need to assign the string back to itself on the LHS:

String a = "[pollTimestamp]";
a = a.replaceAll("[^a-zA-Z0-9] ", "");

However, the following approach might be safer:

String a = "[pollTimestamp]";
a = a.replaceAll("\\[(.*?)\\]", "$1");

This way, we only target a term contained within square brackets. Other types of input would be left alone.

CodePudding user response:

The replaceAll method is attempting to match Non-Alphanumeric Characters. a.replaceAll() produces a new string, please do another assignment a=a.replaceAll().

~ (tilde)
` (grave accent)
! (exclamation mark)
@ (at)

public class Test {
    public static void main(String args[]) {
     String a = "[pollTimestamp]";     
     System.out.print(a.replaceAll("[^a-zA-Z0-9]",""));

  } 
}
  • Related