Search code examples
javaregexstringreplaceall

Replacing more than one character in a String


I am printing an array, but I only want to display the numbers. I want to remove the brackets and commas from the String (leaving only the digits). So far, I have been able to remove the commas but I was looking for a way add more arguments to the replaceAll method.

How can I remove the brackets as well as the commas?

cubeToString = Arrays.deepToString(cube);
System.out.println(cubeToString); 
String cleanLine = "";
cleanLine = cubeToString.replaceAll(", ", ""); //I want to put all braces in this statement too
System.out.println(cleanLine);

The output is:

[[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5]]
[[0000][1111][2222][3333][4444][5555]]

Solution

  • You can use the special characters [ and ] to form a pattern, and then \\ to escape the [ and ] (from your input) like,

    cleanLine = cubeToString.replaceAll("[\\[\\]\\s,]", "");
    

    or replace everything not a digit. Like,

    cleanLine = cubeToString.replaceAll("\\D", "");