Search code examples
javaregexreplaceall

RegEx to remove brackets and blank spaces


I've the following code

String[] helloWorld = {"Hello", "World"};
System.out.println(Arrays.toString(helloWorld));

which prints

[Hello, World]

I need to remove the blank spaces and [ ] . And get the following value.

Hello,World

I've this helloWorld.replaceAll("\\s+","") to remove blank spaces but how do I remove the brackets as well.


Solution

  • Change your regex to :

    String[] helloWorld = {"Hello", "World"};
    System.out.println(Arrays.toString(helloWorld).replaceAll("[\\[\\]\\s]", ""));
    

    Since [ and ] are special symbols in Regex, they have to be escaped.