繁体   English   中英

如何使用Java在字符串中用空格替换(和)方括号

[英]How to replace ( and ) brackets with space in string using java

我在下面的字符串中需要用空格替换(和)

例子1

String str = "Somestring 12with (a lot of braces and commas)";           
System.out.println(str.trim().replaceAll(".*\\(|\\).*", ""));

**预期的输出如下**

   "Somestring 12with a lot of braces and commas"

例子2

String str = "Somestring 12with a lot of braces and commas)";
System.out.println(str.trim().replaceAll(".*\\(|\\).*", ""));

预期产量

"Somestring 12with a lot of braces and commas"

总的来说,我需要从字符串中删除(和)。

您可以使用此正则表达式[()]例如:

str.replaceAll("[()]", "")

输入:

Somestring 12with (a lot of braces and commas) 
Somestring 12with a lot of braces and commas)

输出量

Somestring 12with a lot of braces and commas
Somestring 12with a lot of braces and commas

或者,您可以这样做String newStr = str.trim().replaceAll("\\\\(", "").replaceAll("\\\\)", "");

您的正则表达式将替换之前(或之后)所有内容( .* )
您可以使用:

String resultString = subjectString.replaceAll("[()]", "");

要么 :

String resultString = subjectString.replaceAll("\\(|\\)", "");

我会用第一种方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM