pankaj desai
pankaj desai

Reputation: 93

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

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

Answers (3)

Pedro Lobito
Pedro Lobito

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

TheEllis
TheEllis

Reputation: 1736

Or you could do this String newStr = str.trim().replaceAll("\\(", "").replaceAll("\\)", "");

Upvotes: 2

Youcef LAIDANI
Youcef LAIDANI

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

Related Questions