Reputation: 93
I am having below string where I need to replace ( and ) this with space
Example 1
String str = "Somestring 12with (a lot of braces and commas)";
System.out.println(str.trim().replaceAll(".*\\(|\\).*", ""));
**Expected Output something like below **
"Somestring 12with a lot of braces and commas"
Example 2
String str = "Somestring 12with a lot of braces and commas)";
System.out.println(str.trim().replaceAll(".*\\(|\\).*", ""));
Expected Output
"Somestring 12with a lot of braces and commas"
Overall I need to remove the ( and ) from string.
Upvotes: 1
Views: 3517
Reputation: 98971
Your regex is replacing everything (.*
) before (
or after )
.
You can use:
String resultString = subjectString.replaceAll("[()]", "");
Or :
String resultString = subjectString.replaceAll("\\(|\\)", "");
I'd use the first approach.
Upvotes: 1
Reputation: 1736
Or you could do this String newStr = str.trim().replaceAll("\\(", "").replaceAll("\\)", "");
Upvotes: 2
Reputation: 60026
You can use this regex [()]
for example :
str.replaceAll("[()]", "")
Input:
Somestring 12with (a lot of braces and commas)
Somestring 12with a lot of braces and commas)
Output
Somestring 12with a lot of braces and commas
Somestring 12with a lot of braces and commas
Upvotes: 2