Remove [ ] from string class in Java

In Java, to remove square brackets "[]" from a string, you can use one of the following methods:

Method 1: Use the replace() method

String str = "[Hello World]";
String result = str.replace("[", "").replace("]", "");
System.out.println(result); // 输出:Hello World

In the above code, we use the replace() method to replace the square brackets with an empty string. This will remove the square brackets from the string.

Method 2: Use regular expressions

String str = "[Hello World]";
String result = str.replaceAll("\\[|\\]", "");
System.out.println(result); // 输出:Hello World

In this example, we used the replaceAll() method, which accepts a regular expression as a parameter. The regular expression "\[|\]" means matching square brackets "[" and "]" and then replacing them with an empty string.

No matter which method you choose, you can achieve the effect of removing the square brackets "[]" from the string in Java.

Guess you like

Origin blog.csdn.net/weixin_50503886/article/details/131301589